一、vue.use(vue-router)为例
1、先调用 vue-router插件的install方法
2、install方法里面会传入vue对象方便vue-router方法挂载到vue上面
install(vue)
3、由此建议所有写vue 插件的都要有install方法
虽然说不写install也可以挂载但是不规范啊
import { App } from 'vue';
import { LazyOptions } from './types';
declare const _default: {
/**
* install plugin
*
* @param {App} Vue
* @param {LazyOptions} options
*/
install(Vue: App, options: LazyOptions): void;
};
export default _default;
export const Plugin = {
install(Vue) {
Vue.component...
Vue.mixins...
Vue...
// 我们也可以在install里面执行其他函数,Vue会将this指向我们的插件
console.log(this) // {install: ...,utils: ...}
this.utils(Vue) // 执行utils函数
console.log(this.COUNT) // 0
},
utils(Vue) {
Vue...
console.log(Vue) // Vue
},
COUNT: 0
}
// 我们可以在这个对象上添加参数,最终Vue只会执行install方法,而其他方法可以作为封装install方法的辅助函数
const test = 'test'
export function Plugin2(Vue) {
Vue...
console.log(test) // 'test'
// 注意如果插件编写成函数形式,那么Vue只会把this指向null,并不会指向这个函数
console.log(this) // null
}
// 这种方式我们只能在一个函数中编写插件逻辑,可封装性就不是那么强了