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内容")
}
}
复制代码