Vue 进阶属性
directives、mixins、extends、provide、inject
directives 指令
内置指令
自定义指令
Vue.directive('x', directiveOptions)
Vue.directive('y', {
inserted: function(el) {
el.addEventListener('click', ()=>{console.log('y')})
}
})
new Vue({
...,
directives: {
"x": directiveOptions
}
})
<script>
export default {
name: "HelloWorld",
directives: {
y: {
inserted(el) {
el.addEventListener("click", () => {
console.log("y");
});
},
},
},
props: {
msg: String,
},
};
</script>
directiveOptions
五个函数属性
- bind(el, info, vnode, oldVnode) - 类似 created
- inserted(参数同上) - 类似 mounted
- update(参数同上) - 类似 updated
- componentUpdated(参数同上) - 用的不多
- unbind(参数同上) - 类似 destroyed
缩写
- directiveOptions 在某些条件下可以缩写为函数,用的不多
指令的作用
主要用于 DOM 操作
- Vue 实例/组件用于数据绑定、事件监听、DOM 更新
- Vue 指令主要目的就是原生 DOM 操作
减少重复
- 如果某个 DOM 操作你经常使用,就可以封装为指令
- 如果某个 DOM 操作比较复杂,也可以封装为指令
mixin 混入
类比
- directives 的作用是减少 DOM 操作的重复
- mixins 的作用是减少 data、methods、钩子的重复
技巧
extends 继承、扩展
减少重复
- 遇到与 mixins 同样的需求
- Vue.extend 或 options.extends
const MyVue = Vue.extend({
data(){return {name:'', time:undefined}}
created(){
if(!this.name){console.error(no name!)}
this.time = new Date()
},
beforeDestroy(){
const duration = (new Date()) - this.time
console.log(`${this.name}存活时间${duration}`)
}
})
- 然后就可以使用 new MyVue(options)
provide 和 value
使用
- provide:
Object | () => Object
- inject:
Array<string> | { [key: string]: string | Symbol | Object }
- provide 是祖先组件向子孙后代注入一个依赖
- inject 是让后代注入祖先提供的依赖
示例
var Provider = {
provide: {
foo: 'bar'
},
}
var Child = {
inject: ['foo'],
created () {
console.log(this.foo)
}
}
总结
- 作用:大范围的 data 和 method 等共用
- 注意:不能只传值不传方法,因为值是被复制给 provide的
- 可以传引用但不推荐,容易失控