一、插件通常用来为 Vue 添加全局功能。
1、添加全局方法或者 property。
2、添加全局资源:指令/过滤器/过渡等。如 vue-touch
3、通过全局混入来添加一些组件选项。如 vue-router
4、添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
5、一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
插件的功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
在vue中自定义全局插件的使用
二、新建一个plugins.js文件,在其自定义一些插件
插件是一个对象必须实现install办法
插件需要在vue文件中使用Vue.use插
插件方法
- Vue.extend (.vue文件)继承.Vue文件的构造函数
- instance.$mount(dom)手动挂载
- Vue.prototype.$toast=Toast将插件挂载到全局的(所有组件的实例都将拥有插件的方法和属性)
//01 导入vue
import NotifyVue from './NotifyVue'
//定义插件
const Notify = {}
//实现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 同步插件 Notify和NotifyVue实例的方法
Notify.show = instance.show;
Notify.hide = instance.hide;
Notify.success = instance.success;
Notify.danger = instance.danger;
Notify.warning = instance.warning;
//挂载到全局
Vue.prototype.$notify = Notify;
}
//导出
export default Notify
//定义一个插件他是一个对象
import ToastVue from './ToastCom.vue'
var Toast = {}
Toast.install = function (Vue) {
//vue 的插件必须实现install方法
var ToastCom = Vue.extend(ToastVue);
var instance = new ToastCom();
instance.$mount(document.createElement("div"))
document.body.appendChild(instance.$el)
Toast.show = instance.show;
Toast.hide = instance.hide;
Vue.prototype.$toast = Toast;
}
//导出插件
export default Toast