引子:
读到vue官网教程的最后一课:插件,教学有点简单,看完比较懵逼,所以找了大神的资料作为参考:
参考资料:
官方:https://cn.vuejs.org/v2/guide/plugins.html
大神劳卜:https://www.cnblogs.com/luozhihao/p/7414419.html
解读:
插件不同于组件,官网中的组件为Vue.component()生成引入,而插件是我们常用的ui框架中的各种插件,比如有赞框架的vant的Toast插件,需要通过Vue.use(Toast)引入。
插件制作:
一个插件应该需要dom结构,js方法,以及必要的css样式,其.vue文件和我们之前写的component组件差不多,index.js是生成插件的js方法,大致的目录格式是这样的:
首先:先写Loading.vue,敲出我们想要的插件ui以及功能
<!--Loading.vue-->
<template>
<transition name="fade">
<div class="loading" v-if="show">
<div class="loading-icon"></div>
</div>
</transition>
</template>
<script>
export default{
data(){
return {
show: false
}
},
methods: {
open(){
this.show = true;
},
close(){
this.show = false;
}
}
}
</script>
<style scoped="scoped">
.loading {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0,0,0,.5);
color: #fff;
text-align: center;
z-index: 9999!important;
}
.loading-icon {
width: 65px;
height: 65px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-image: url('./loading.gif');
background-size: 100% 100%;
}
.fade-enter-active,
.fade-leave-active {
transition: 0.3s ease-out;
}
.fade-enter {
opacity: 0;
}
.fade-leave-to {
opacity: 0;
}
</style>
你可以通过路由先看看插件的样子,不过记得把show的值改为ture,不然看不到哦!~
然后开始生成插件:
// 导入loading插件的dom,js,css
import LoadingComponent from './Loading.vue';
// 设置插件名,对外暴露
const Loading = {};
// install是插件注册的主要方法,带2个参数(Vue构造器和自定义配置属性options)
Loading.install = function (Vue, options) {
// 此4步是将插件导入到开发代码中
const LoadingConstructor = Vue.extend(LoadingComponent);
const instance = new LoadingConstructor();
instance.$mount(document.createElement('div'));
document.body.appendChild(instance.$el);
// 注册插件的对外方法,在注册后可直接.open()开启loading,close()隐藏loading
Loading.open = () => {
instance.show = true
};
Loading.close = () => {
instance.show = false
};
// 注册插件的Vue实例原型上的$loading方法,注册后可直接this.$loading.open()或Vue.prototype.$loading.open()开启,this.$loading.close()隐藏
Vue.prototype.$loading = {
open:() => {
instance.show = true
},
close:() => {
instance.show = false
}
};
// 设置方法为window变量,注册后可Toast.open()开启
window.Toast = {
open:() => {
instance.show = true
},
close:() => {
instance.show = false
}
}
};
export default Loading;
使用:
// src/main.js
import Toast from './plugin/loading/index.js';
Vue.use(Toast);
拓展:
官方文档中还提供了插件的丰富功能,你可以增加插件的混入,指令,原型等:
Loading.install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
以下图片资料源自于大神劳卜: