Vue的plugin属性
功能:用于增强Vue
本质: 包含install方法的一个对象,install的第一个参数是Vue, 第二个以后得参数是插件使用者传递的数据。
1. 插件使用步骤
1.1 定义插件
js
对象.install = function(Vue, options){ //定义对象的install方法
// 1. 添加全局过滤器
Vue.filter(...)
// 2. 添加全局指令
Vue.directive(...)
// 3. 配置全局混入(合)
Vue.mixin(...)
// 4. 添加实例方法
Vue.prototype.$myMethod = function() {...}
Vue.prototype.$myProperty = xxx
}
1.2 使用插件
使用插件: Vue.use() 其中Vue.use()还可以传递参数,比如Vue.use(plugins, a,b, c)
js
// 引入vue
import Vue from 'vue'
// 引入App组件,它是所有组件的父组件
import App from './App.vue'
// 关闭vue的生产提示
Vue.config.productionTip = false
import plugins from "@/plugins";
Vue.use(plugins)
// 创建vm实例对象
new Vue({
// 将App组件放到容器中
render: q => q(App)
}).$mount('#app')
js
export default {
install(Vue) {
// 全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 4)
})
Vue.directive('fbind', {
// 指令与元素成功绑定时(一上来)
bind(element, binding) {
element.value = binding.value
},
// 指令所在元素插入页面时候
// eslint-disable-next-line no-unused-vars
inserted(element, binding){
element.focus()
},
// 指令所在元素被重新解析时
update(element, binding){
element.value = binding.value
}
})
Vue.mixin({
data(){
return {
a: 100
}
}
})
// Vue原型上添加方法
Vue.prototype.hello = () =>{ alert('你好啊!')}
}
}
运行效果: