在沒有封裝組件之前,如果不使用第三方插件,那么很多情況下我們會編寫幾個常用的組件來提供給頁面使用,如Alert/Loading組件,而你可能需要在很多頁面中引入並且通過components注冊組件,但是像這樣使用率很高的組件一般我們希望全局注冊后直接就可以在相應頁面使用,因此我們需要將他們封裝成插件。
vue插件的編寫方法一般分為4類,如上圖所示。主要注冊與綁定機制如下:
export default { install(Vue, options) { Vue.myGlobalMethod = function () { // 1. 添加全局方法或屬性,如: vue-custom-element // 邏輯... } Vue.directive('my-directive', { // 2. 添加全局資源:指令/過濾器/過渡等,如 vue-touch bind (el, binding, vnode, oldVnode) { // 邏輯... } ... }) Vue.mixin({ created: function () { // 3. 通過全局 mixin方法添加一些組件選項,如: vuex // 邏輯... } ... }) Vue.prototype.$myMethod = function (options) { // 4. 添加實例方法,通過把它們添加到 Vue.prototype 上實現 // 邏輯... } } }
實戰:loading
//loading.vue
<template> <div class="loading-box" v-show="show"> <div class="loading-mask"></div> <div class="loading-content"> <div class="animate"> </div> <div class="text">{{text}}</div> </div> </div> </template> <script> export default { props: { show: Boolean, text: { type: String, default: '正在加載中...' }, } } </script>
<style>
...
</style>
下面我們便來封裝一下該組件:
// loading.js import LoadingComponent from './components/loading.vue' let $vm export default { install(Vue, options) { if (!$vm) { const LoadingPlugin = Vue.extend(LoadingComponent); $vm = new LoadingPlugin({ el: document.createElement('div') }); document.body.appendChild($vm.$el); } $vm.show = false; let loading = { show(text) { $vm.show = true; $vm.text = text; }, hide() { $vm.show = false; } }; if (!Vue.$loading) { Vue.$loading = loading; } // Vue.prototype.$loading = Vue.$loading; Vue.mixin({ created() { this.$loading = Vue.$loading; } }) } }
目錄結構:

首頁:this.$loading.show('') this.$loading.hide()
created () {
this.$loading.
show(
'')
axios.
get(url.getIconList).
then(
res
=> {
if (res.status
===
200) {
this.iconList
= res.data.iconlist
this.$loading.
hide()
}
}).
catch(
error
=> {
console.
log(error)
})
}

