问题:
学习自定义指令时候,在directive/index.js中有这样一段代码:
import copy from "./copy";
export default {
install(Vue) {
Vue.directive('copy', copy);
},
};
几天后,看到一个帖子组件的引用方法,在directive/index.js中也有这样一段代码
import Modal from './modal.vue';
export default {
install(Vue) {
Vue.component('Modal', Modal);
},
};
全局注册
...
import Directives from '@/directives';
//重点
Vue.use(Directives);
...
又去官网去重新了解了一番
install是开发插件的方法,这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
总结:
install方法封装完毕后,需要在全局或者单独组件去用vue.use()注册一下使用
应用场景:
自定义指令或者封装组件不想要每次都引入的话,就可以全局暴露出去,然后单独组件直接引用