vue插件开发主要是用来实现一些全局方法或者全局对象。Vue的插件要求是实现一个install公开方法。其中此install方法的第一个入参是Vue构造器,第二个入参是
是一个可选的选项对象。
一、开发
以一个Alert的弹窗插件为示例,Alert.js;
- 定义一个全局变量Alert ,var alert;
- 对Alert定义一个全局公开方法install,alert.install = function(vue ,options){...}
- 在Vue的prototype添加实例方法$alert,Vue.prototype.$Alert = ({msg="", type, isShow=false} = options) => {...}
- 创建Vue组件,let AlertComponent = Vue.extend(Component);
- 将上一步创建的组件实例,挂载到body上。
具体代码如下:
//定义一个全局变量Alert
var Alert = {}
//对Alert定义一个全局公开方法install
Alert.install = function (Vue, options) {
let isShow = false;
let currentVM = null;
//在Vue的prototype添加实例方法$alert
Vue.prototype.$Alert = ({msg="", type, isShow=false} = options) => {
let iPop = type =="error"? 'i-popWarn': 'i-popRight';
msg = msg ? msg: type == 'success'?'操作成功': type == 'error'?'操作失败</br>请稍后再试': '未知错误';
let AlertComponent = Vue.extend({ //创建Vue组件
data: () => {
return {
show: isShow,
pop: iPop,
msg: msg
}
},
template:'<div v-show="show"><i :class=pop> </i></br>{{msg}}</div>'
})
currentVM = new AlertComponent(); // 实例化组件
let tmpl = currentVM.$mount().$el; // 获取组件挂载的元素
document.body.appendChild(tmpl); // 将组件添加到body
}
Vue.prototype.$Alert['show'] = ({msg="", type} = options) => {
isShow = true;
return Vue.prototype.$Alert({msg, type, isShow})
}
Vue.prototype.$Alert['hide'] = () => {
return Vue.prototype.$Alert({isShow: false})
}
}
export default Alert;
上面是一种基本的写法,还可以使用Object.defineProperty方法直接将写好的对象直接赋值到Vue.prototype上。
import Alert from '.Alert'
export default {
install (Vue) {
function construct(options) {
var constructer = Vue.extend(Alert);
var instance = new constructer();
instance.vm = instance.$mount();
for(var key in options) {
instance.vm[key] = options[key];
}
document.querySelector('body').appendChild(instance.vm.$el);
instance.dom = instance.vm.$el;
return instance;
}
var o = {
show (msg, options = {}) {
var instance = construct(options);
instance.vm.msg = msg;
instance.vm.isShow = true;
},
hide (retcode = 0, retmsg = 'ok', options = {}) {
var instance = construct(options);
instance.vm.isShow = false;
}
}
Object.defineProperty(Vue.prototype, '$alert', {value: o});
}
}
其中Alert组件略。
二、使用
通过全局方法 Vue.use() 使用插件,即:
import Alert from '/plugins/Alert'
Vue.use(Alert);
参考资料: Vue插件