Vue插件
插件是一个对象,必须实现install办法
插件需要在vue文件中使用Vue.use(插件)
插件方法
Vue.extend(.vue文件) 继承.vue文件的构造函数
instance.mount(dom)手动挂载instance.mount(dom) 手动挂载
instance.mount(dom)手动挂载instance.el 实例的真实dom
Vue.prototype.$toast=Toast 将插件挂载到全局的(所有组件的方法和属性)
Notify通知插件
index.js
// 01 导入组件
import NotifyVue from './NotifyCom.vue'
// 定义一个插件他是一个对象
var Notify={}
// Vue的插件必须实现install方法
Notify.install=function(Vue){
// 02 获取组件的构造函数
var NotifyCom=Vue.extend(NotifyVue)
// 03 创建组件的实例
var instance=new NotifyCom();
// 04 挂载到真实的dom
instance.$mount(document.createElement("div"));
// 05 插入到body
document.body.appendChild(instance.$el);
// 06 关联Toast 插件
Notify.show = instance.show;
Notify.hide = instance.hide;
Notify.success = instance.success;
Notify.danger = instance.danger;
Notify.warning = instance.warning;
// 把当前对象挂载到Vue的原型上
// Vue所有的组件和实例都可以使用$toast放
Vue.prototype.$notify=Notify
}
// 导出插件
export default Notify
NotifyVue.vue
<template>
<div class="notify" v-if="msg" :style="{color:color,backgroundColor:bgColor}">
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data() {
return {
//通知文本
msg: "",
//文本颜色
color: "#fff",
//背景颜色
bgColor: "#090"
}
},
methods: {
//显示通知
show(msg,bgColor='#090',color='#fff') {
this.msg = msg;
this.bgColor = bgColor;
this.color = color;
setTimeout(() => {
this.hide();
}, 2000)
}
},
hide() {
this.msg = "";
},
//成功
success(msg){
this.show(msg,'#090')
},
//失败
danger(msg){
this.show(msg,'#ff5500')
},
//警告
warning(msg){
this.show(msg,'#ffd606')
}
}
</script>
<style scoped="scoped">
.notify {
height: 44px;
line-height: 44px;
position: fixed;
width: 100vw;
left: 0;
top: 0;
text-align: center;
}
</style>
main.js
//导入插件
import Notify from '@/plugin/Notify/index'