插件
功能: 用于增强Vue
本质: 包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数
据。
定义插件:
对象.install = function(Vue,options) {
// 1.添加全局过滤器
Vue.filter(...)
// 2.添加全局指令
Vue.directive(...)
}
定义插件
plugins.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
},
// 指令所在元素被插入页面时
inserted(element,binding){
console.log(binding)
element.focus()
},
// 指令所在的模板被重新解析时
update(element,binding){
element.value=binding.value
}
})
// 定义混入
Vue.mixin({
data(){
return {
x:100,
y:200
}
}
})
//给Vue原型上添加一个方法(vm和vc都可以用)
Vue.prototype.dello = ()=> {alert('你好')}
}
}
全局应用
main.js
// 引入vue
import Vue from 'vue'
//引入App
import App from './App'
// 引入插件
import plugins from './plugins'
// 关闭Vue的生产提示
Vue.config.productionTip = false
//应用(使用)插件
Vue.use(plugins)
// 创建Vue
new Vue({
render:h=>h(App)
}).$mount("#app")
<template>
<div>
<h2>学校名字: {{name | mySlice}}</h2>
<h2>学校地址: {{address}}</h2>
<input type="text" v-fbind:value="name">
<!-- <button @click="test">点我触发hello</button> -->
<button @click="dello">点我触发hello</button>
</div>
</template>
<script>
export default {
name:'Student',
data () {
return {
name:'blibli啊啊啊啊啊',
address:'无锡'
};
},
methods: {
// test(){
// this.dello()
// }
},
}
</script>