由于最近在做一些前端的項目,并且接手了Weex的項目,所以難免和Vue打起了交道,js也是從入門到學習中。項目里用到了Vue的插件機制,所以看了看Vue.use的源碼,還是比較簡單的,適合新手閱讀,所以記錄下來以免遺忘。
感謝
本文最后一章節[結合實際場景]是參考了eros 這個開源項目的,感謝eros項目組的開發。
什么是Vue插件
關于什么是Vue插件大家可以去看官網的解釋 ,總得來說就是提供一個全局注冊/調用的能力。
怎么用
我們以Weex為例。
首先有一個toast.js
const Toast = {}
Toast.install = (Vue, options) => {
Vue.prototype.$toast = (msg, duration = 0.8) => {
const modal = weex.requireModule('modal')
modal.toast({
message: msg,
duration: 0.8
})
}
}
Vue.use(Toast)
很簡單,就是定義了一個Toast對面,然后給Toast對象創建一個install方法,方法里給Vue的prototype創建了一個$toast方法,該方法就是調用modal去彈一個toast,最后使用Vue.use方法去注冊這個Toast插件。
然后我們還有一個index.vue:
<template>
<div>
<div class="box" @click="onclick" @longpress="onlongpress" @appear="onappear" @disappear="ondisappear"></div>
</div>
</template>
<script>
const modal = weex.requireModule('modal')
export default {
methods: {
onclick (event) {
this.$toast("aaa", 0.8)
},
onlongpress (event) {
console.log('onlongpress:', event)
modal.toast({
message: 'onlongpress',
duration: 0.8
})
},
onappear (event) {
console.log('onappear:', event)
modal.toast({
message: 'onappear',
duration: 0.8
})
},
ondisappear (event) {
console.log('ondisappear:', event)
modal.toast({
message: 'ondisappear',
duration: 0.8
})
}
}
}
</script>
<style scoped>
.box {
border-width: 2px;
border-style: solid;
border-color: #BBB;
width: 250px;
height: 250px;
margin-top: 250px;
margin-left: 250px;
background-color: #EEE;
}
</style>
在其中調用了this.$toast去使用插件的方法。
由此我們可以知道,Vue的插件機制就是通過Vue.use方法去注冊的。
源碼分析
Vue.use = function (plugin) {
if (plugin.installed) {
return
}
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);
}
plugin.installed = true;
return this
};
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
use方法非常簡單:
0x01:判斷該插件是否已經注冊,如果已經注冊就直接return,防止重復注冊。
0x02:然后通過toArray方法將Arguments這個類數組轉換成真正的數據,并且去掉第一個元素。
0x03:將this,也就是Vue實例添加到toArray生成的args數組中。
0x04:判斷use的入參plugin是install是否是一個方法,如果是則直接調用該方法。
0x05:如果第四步是false,則判斷plugun本身是不是一個方法,如果是方法,則用它本身代替install去執行。
0x06:將plugin的installed標記位設置為true。
就這么簡單的6步,use方法就分析完了,其實就是為了去執行插件的install方法,而結合上面的例子我們知道,install中就把$toast賦值給了Vue的prototype,在其他地方就可以使用的。
結合實際場景
學習了Vue的插件機制,那么這個機制我們能用來做什么呢?我們結合Weex來看。
首先我們知道,Weex是把bundle下發到客戶端并渲染,所以一個頁面的加載時間取決于兩部分:bundle下載時間,bundle渲染時間。在不考慮本地緩存的情況下,bundle的大小直接決定了它的下載時間,以及用戶所消耗的流量,所以我們需要有一種方式去盡可能的減小這個bundle的體積。這里Vue的插件機制就可以排上用場了。
首先我們把一部分共用,不太會改動的基礎的代碼放在客戶端,這樣bundle里的內容就應該是純業務相關的代碼,在把bundle下載下來之后手動將客戶端的基礎js拼接到bundle上,這樣就能有效地減小bundle的體積,而想要使用這種方式,就必須把基礎js通過Vue的插件機制注冊,業務js中全局調用,不然是無法拼接的(除非你的基礎js不通過webpack打包),畢竟webpack打包之后所有的代碼都是封閉的,無法互相調用。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。