Vue.js 的插件應當有一個公開方法 install 。這個方法的第一個參數是 Vue 構造器 , 第二個參數是一個可選的選項對象:vue
MyPlugin.install = function (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 上實現
// 邏輯...
}
}複製代碼
目錄結構:node
nwd-loading.vue:vuex
<template>
<div class="nwd-loading" v-show="show">
<div>{{text}}</div>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
text: "正在加載中..."
}
}
</script> 複製代碼
index.jsbash
import NwdLoadingComponent from './nwd-loading'
let $vm;
export default {
install(Vue,options) {
if(!$vm) {
const NwdLoadingPlugin = Vue.extend(NwdLoadingComponent);
$vm = new NwdLoadingPlugin({
el: document.createElement('div')
});
}
$vm.show = false;
let loading = {
show(text) {
$vm.show = true;
$vm.text = text;
document.body.appendChild($vm.$el);
},
hide() {
$vm.show = false;
}
};
if (!Vue.$loading) {
Vue.$loading = loading;
}
// Vue.prototype.$loading = Vue.$loading;
Vue.mixin({
created() {
this.$loading = Vue.$loading;
}
})
}
}複製代碼
註釋:經過Vue.extend()方法建立了一個構造器NwdLoadingPlugin,其次咱們再經過new NwdLoadingPlugin() 建立了實例$vm,並掛載到一個div元素上。最後咱們須要經過document.body.appendChild($vm.$el)將其插入到DOM節點中。app
當咱們建立了$vm實例後,咱們能夠訪問該實例的屬性和方法,好比經過$vm.show就能夠改變NwdLoadingComponent組件的show值來控制其顯示隱藏。ide
最終咱們經過Vue.mixin或者Vue.prototype.$loading來全局添加了$loading事件,其又包含了show和hide兩個方法。咱們能夠直接在頁面中使用this.$loading.show()來顯示加載,使用this.$loading.hide()來關閉加載。學習
main.jsui
import NwdLoading from '@/components/nwd-loading/index.js'
Vue.use(NwdLoading)
複製代碼
....vuethis
export default {
created() {
this.$loading.show("loading內容")
}
}
複製代碼