功能:用于增強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 = xxxx
}
使用插件:Vue.use()
例子:
創(chuàng)建plugins.js文件
export default {
install(Vue) {
//可以定義全局過濾器
Vue.filter("mySclice", function (value) {
return value.slice(0, 4)
})
//定義全局指令
Vue.directive('fbind', {
//指令與元素綁定時
bind(element, binding) {
element.value = binding.value
},
//指令所在元素被插入頁面時
inserted(element, binding) {
element.focus()
},
//指令所在模版被重新解析時
update(element, binding) {
element.value = binding.value
}
})
//定義混入
Vue.mixin({
data() {
return {
x: 100,
y: 200
}
},
})
//給Vue原型上添加一個方法
Vue.prototype.hello = () => {
}
}
}
使用,main.js中:
//插件
import plugins from './plugins'
Vue.use(plugins)