1.在根目录 -新建文件夹: message。 2.新建-vue文件: message.vue。
<template>
<div class="message-content" v-show="show" :class="type">
<span class="text">{{text}}</span>
</div>
</template>
<script>
export default {
name: '',
props:{
type:{
type:String,
default:''
},
text:{
type:String | Object,
default:''
},
show:{
type:Boolean,
default:false
}
},
data() {
return {
}
}
}
</script>
<style scoped>
.message-content{
position: fixed;
right: 0px;
top:40px;
min-width: 400px;
padding: 10px 20px;
background-color: #555;
color:#333;
}
.message-content.info{
background-color: indianred;
}
.message-content.success{
background-color: saddlebrown;
}
</style>
3.新建js index.js。
import msgs from './message.vue'
const MESSAGE ={
show:true,
duration:1000,
install(Vue) {
if (typeof window !== 'undefined' && window.Vue) {
Vue = window.Vue
}
Vue.component('Message', msgs);
function msg(type, text, callBack) {
let msg
let duration = MESSAGE.duration
if (typeof text === 'string') {
msg = text
} else if (text instanceof Object) {
msg = text.text || ''
if (text.duration) {
duration = text.duration
}
}
let VueMessage = Vue.extend({
render(h) {
let props = {
type,
text:msg,
show: this.show
}
return h(msgs, {
props
})
},
data() {
return {
show: false
}
}
})
let newMessage = new VueMessage()
let vm = newMessage.$mount()
console.log(vm,'istall vmmm')
let el = vm.$el
document.body.appendChild(el) // 把生成的提示的dom插入body中
vm.show = true
let t1 = setTimeout(() => {
clearTimeout(t1)
vm.show = false //隐藏提示组件,此时会有300ms的动画效果,等动画效果过了再从body中移除dom
let t2 = setTimeout(() => {
clearTimeout(t2)
document.body.removeChild(el) //从body中移除dom
newMessage.$destroy()
vm = null // 设置为null,好让js垃圾回收算法回收,释放内存
callBack && (typeof callBack === 'function') && callBack()
}, MESSAGE.duration)
}, MESSAGE.duration)
}
Vue.prototype.$message = {
info(text, callBack) {
if (!text) return
msg('info', text, callBack)
},
success(text, callBack) {
if (!text) return
msg('success', text, callBack)
},
error(text, callBack) {
if (!text) return
msg('error', text, callBack)
},
warning(text, callBack) {
if (!text) return
msg('warning', text, callBack)
}
}
}
}
export default MESSAGE
4.main.js 引入
import message from './message /index.js'
Vue.use(message );
5.组件内使用
该插件,支持四种类型的 message提示框,message默认延迟:1s, 样式自行修改。
this.$message.info('韦德牌男人', function callBack(){
alert ('我消失了')
})
this.$message.success('韦德牌男人', function callBack(){
alert ('我消失了')
})
this.$message.error('韦德牌男人', function callBack(){
alert ('我消失了')
})
this.$message.warning('韦德牌男人', function callBack(){
alert ('我消失了')
})
例如:
内容:对象(类型)
mounted () {
this.$message.success({text:'韦德拍男人',duration:3000} , function callBack(){
alert ('我消失了')
})
}
内容:字符串(类型)
mounted () {
this.$message.success('韦德牌男人', function callBack(){
alert ('我消失了')
})
}