38vue中plugin插件的使用
vue中plugin插件的使用
- 全局过滤器(filter)
- 全局指令(directive)
- 全局混入(mixin)
- 全局方法(原型)
- ...
插件
功能: 用于增强Vue
本质: 包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
定义插件:
对象.install = function (Vue, options){
// 1.添加全局过滤器
Vue.filter(....)
// 2.添加全局指令
Vue.directive(....)
// 3.配置全局混入
Vue.mixin(....)
//4。添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxx
}
使用插件:Vue.use()
或
export default {
install(Vue, options){
......
}
}
实例
export const plugins = {
install(Vue,options) {
console.log('Installing...')
console.log('Vue', Vue) // Vue构造函数
// 1.全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 4)
})
// 2.全局自定义方法
Vue.directive('fbind', {
// 钩子
bind(element, binding) {
console.log(this, 'bind')
element.value = binding.value;
},
inserted(element, binding) {
console.log(this, 'inserted')
element.focus();
},
update(element, binding) {
console.log(this, 'update')
element.value = binding.value;
}
})
// 3.全局混入
Vue.mixin({
methods: {
showName() {
alert(this.name)
}
}
})
// 4.Vue.prototype.xxx 定义原型方法or属性
Vue.prototype.myProp = 200;
Vue.prototype.$myFunc = () => console.log(this);
}
}

浙公网安备 33010602011771号