![20363eeaf3d8c1c13ee488024f06c94e.png](https://img-blog.csdnimg.cn/img_convert/20363eeaf3d8c1c13ee488024f06c94e.png)
vue.extend
请注意,extend创建的是一个组件构造器,而不是一个具体的组件实例。所以他不能直接在Vue实例中这样使用:components: componentName,最终还是要通过Vue.components注册才可以使用的。
首先创建一个alert.vue
<template>
<div class="alert" :class="type" v-show="show">
<i class="icon"></i>
<span class="text">{{text}}</span>
</div>
</template>
<script>
export default {
props: {
type: {type: String,default: 'info',validator: val => ['info', 'success', 'warning', 'error'].includes(val)//['info', 'success', 'warning', 'error'] 表示type只接收这四个字符串作为参数传入message组件},
text: {type: String,default: ''},
show: {type: Boolean,default: false}
}
}
</script>
<style scoped>
.alert{
position: fixed;
top: 40px;
left: 50%;
transform: translateX(-50%);
//其余的样式
}
</style>
然后再创建一个alert.js
import alert from './alert.vue'
const alert= {
duration: 2000, // 显示 ms
animateTime: 200, // 动画时间
install(Vue) {
// Vue.use(plugins:object || function,args)的第一个参数是对象或者方法,
//如果是对象,就执行对象中的install方法,否则就直接执行传入方法。
// plugins的第一个参数是当前的Vue实例,其余参数是传入的args
if (typeof window !== 'undefined' && window.Vue) {
Vue = window.Vue
}
Vue.component('Message', Message)
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('message', {props})
},
data() {
return {
show: false
}
}
})
let newMessage = new VueMessage()
let vm = newMessage.$mount()
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.animateTime)
}, duration)
}
// 挂载到vue原型上,暴露方法
Vue.prototype.$alert= {
info(text, callBack) {
if (!text) return
msg('info', text, callBack)
},
//success error warning同上
}
}
}
export default alert
然后在main.js中注册
import alert from './alert.js'
Vue.use(alert)
注册之后就可以使用了
this.$alert.info("info text")//success error等
在之前的代码示例中,可以看到vue.use做了什么
Vue.use(plugins:object || function,args)的第一个参数是对象或者方法,
如果是对象,就执行对象中的install方法,否则就直接执行传入方法。
plugins的第一个参数是当前的Vue实例,其余参数是传入的args