由于最近在做一些前端的項目,并且接手了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}
新聞熱點
疑難解答
圖片精選