七、插件
1、插件初定义
Vue.js 的插件必须暴露一个 install
方法。其第一个参数是 Vue
构造器,第二个参数是一个可选的选项对象
1、新建一个插件文件
名字随便起,我这里叫 myPlugin.js
export default {
install(Vue, ...x){
console.log('Vue==>', Vue)
console.log('x==>', x)
}
}
2、Vue注册自定义插件
没错!就是在 main.js 里 new Vue之前注册
// ...
//引入插件
import plugin from './myPlugin'
// 应用(使用)插件
Vue.use(plugin, 1, '2', { a: 666 })
//创建vm
new Vue({
// ...
})
3、Result
2、玩转插件
1、在插件里来个大杂烩
export default {
install(Vue, ...x){
console.log('Vue==>', Vue)
console.log('x==>', x)
// 整个全局过滤器
Vue.filter('mySlice', function(value){
return value.slice(0,4)
})
// 再定义个全局指令
Vue.directive('fbind',{
// 指令与元素成功绑定时(一上来)
bind(element, binding){
element.value = binding.value
},
// 指令所在元素被插入页面时
inserted(element){
element.focus()
},
// 指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
// 混入也不能落下
Vue.mixin({
data() {
return {
x: 100,
y: 200
}
},
})
// 再给Vue原型上添加一个方法(vm和vc就都能用了~)
Vue.prototype.sayHi = ()=>{ alert('Hi~') }
// 只要你想,你可以在这里干任何事情!
}
}
2、CODE
1、项目结构
2、main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugin from './myPlugin'
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用(使用)插件
Vue.use(plugin, 1, '2', { a: 666 })
//创建vm
new Vue({
el:'#app',
render: h => h(App)
})
3、App.vue
<template>
<div>
<Student/>
</div>
</template>
<script>
import Student from './components/Student'
export default {
name:'App',
components:{Student}
}
</script>
4、Student.vue
<template>
<div>
<h2>学生姓名:{{name | mySlice}}</h2><!-- 测试全局过滤器 -->
<h2>学生性别:{{sex}}</h2>
<button @click="sayHi">点我测试一个sayHi方法</button><br/>
x+y:<input type="text" v-fbind:value="x + y">
</div>
</template>
<script>
export default {
name:'Student',
data() {
return {
name: 'Mr.Wang',
sex: '男'
}
},
}
</script>
3、Result
3、插件总结
-
功能:用于增强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()