1. 使用
1.1 官網(wǎng)地址
1.2 插件使用方式
let MyPlugin = {
install(Vue, args) {
//邏輯...
}
};
let MyPlugin2 = function(Vue, args) {
//邏輯...
};
Vue.use(MyPlugin, {
options: "MyPlugin1"
});
Vue.use(MyPlugin2, {
options: "MyPlugin2"
});
1.3 demo
<!DOCTYPE html>
<html>
<head>
<title>Vue插件</title>
<!-- 填寫vue地址 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 使用方式一 定義MyPlugin, MyPlugin是個對象,包含一個install屬性,install對應(yīng)一個函數(shù)。
let MyPlugin = {
install(Vue, args) { //Vue對應(yīng)全局的Vue構(gòu)造函數(shù),用作后續(xù)的屬性、指令、混入、原型對象的擴展
console.log(Vue, args)
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 邏輯...
}
})
// 3. 注入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}
}
// 使用方式二 定義MyPlugin2, MyPlugin2本身就是個函數(shù)
let MyPlugin2 = function (Vue, args) {
console.log(Vue, args)
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 邏輯...
}
})
// 3. 注入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}
</script>
</head>
<body>
<div id="demo">
<p>{{foo}}</p>
</div>
<script>
Vue.use(MyPlugin, {
options: "MyPlugin1"
})
Vue.use(MyPlugin2, {
options: "MyPlugin2"
})
const app = new Vue({
el: '#demo',
data: { foo: 'foo' }
})
</script>
</body>
</html>
2. 源碼
/* @flow */
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) { //這里能看到Vue.use傳入的plugin可以是函數(shù)也可以是對象
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) { //自動阻止多次注冊相同插件,屆時即使多次調(diào)用也只會注冊一次該插件。
return this
}
// additional parameters
// Vue.use(MyPlugin, arg)
// install(Vue)
const args = toArray(arguments, 1) //獲取Vue.use(plugin, args)中的args,args是用戶傳入的自定義配置項
args.unshift(this) // 往args前面插入當(dāng)前Vue對象,所以后續(xù)的回調(diào)函數(shù)的第一個參數(shù)就是這個Vue對象
if (typeof plugin.install === 'function') {//如果傳入的plugin.install 是函數(shù)類型,則回調(diào)這個install函數(shù)
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') { //如果傳入的plugin本身是函數(shù)類型,直接回調(diào)plugin函數(shù)本身
plugin.apply(null, args)
}
installedPlugins.push(plugin) //installedPlugins 緩存?zhèn)魅氲膒lugin
return this
}
}
2.1 源碼所在文件位置
src/core/global-api/use.js
3 后續(xù)
本文簡單的記錄了學(xué)習(xí)vue源碼的過程中,關(guān)于插件相關(guān)源碼的解讀。文章中如果有任何的錯誤,歡迎拍磚!