在vue中使用插件的源碼如下:
如果我們使用插件可以在插件內(nèi)部定義install方法或者export的就是個(gè)函數(shù)币他,看了vuex和vue-route的源碼都是使用install方法蹭沛,所以我在這里就用通常的install方法去實(shí)現(xiàn)
function initUse (Vue) {
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}
第一步 使用 vue init webpack vue-plugin 搭建vue腳手架項(xiàng)目
第二步赂韵,創(chuàng)建完項(xiàng)目排截,在src目錄創(chuàng)建plugin.js,代碼如下嫌蚤,在install方法里定義了一個(gè)全局方法辐益,一個(gè)實(shí)例方法:
var myPlugin = Object.create(null);
myPlugin.install = function (Vue, options) {
// 1. 添加全局方法或?qū)傩? Vue.myGlobalMethod = function () {
console.log('我是全局方法')
}
// 2. 添加實(shí)例方法
Vue.prototype.$myMethod = function (methodOptions) {
console.log('我是實(shí)例方法')
}
}
export default myPlugin
第三步 在main.js引入,調(diào)用myGlobalMethod全局方法
import Vue from 'vue'
import App from './App'
import router from './router'
import myPlugin from './plugin'
Vue.config.productionTip = false
Vue.use(myPlugin)
Vue.myGlobalMethod()
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
第四步 在HelloWorld.vue文件created里調(diào)用$myMethod()實(shí)例方法
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
created(){
this.$myMethod();
}
}
第五步 運(yùn)行項(xiàng)目脱吱,查看結(jié)果智政,兩個(gè)方法都運(yùn)行成功,簡單的插件已經(jīng)完成了
image.png