Vue进阶属性
directives
, mixins
, extends
, provide
, inject
内置指令
v-if
,v-for
,v-show
,v-html
自定义指令
声明一个全局指令
Vue.directive('x',directiveOptions)
就可以在任何组件里使用v-x
了
directiveOptions
是选项
声明一个局部指令
new Vue({
...,
directives: {
"x": directiveOptions
}
})
//v-x只能在该实例中使用。
directiveOptions
- bind(el, info, vnode, oldVnode)-类似created
- inserted(参数同上)-类似mounted
- update(参数同上)-类似updated
- componentUpdated(参数同上)-用的不多
- unbind(参数同上)-类似destroyed
el:绑定的元素
info:除了传元素之外,还传了那些东西(详细的信息)
vnode:元素对应的虚拟节点
oldVnode:之前的虚拟节点
模仿v-on
import Vue from 'vue';
new Vue({
template: `
<button v-on:click='hi'>点我</button>
`,
methods: {
hi(){
console.log("hi");
}
}
}).$mount("#app");
上面是使用v-on
的写法
下面是使用自定义指令的写法
import Vue from 'vue';
new Vue({
directives: {
'on2': {
inserted(el, info){
el.addEventListener(info.arg, info.value)
},
unbind(el, info){
el.removeEventListener(info.arg, info.value)
}//当元素移除时,就去掉这个事件
}
},
template: `
<button v-on2:click='hi'>点我</button>
`,
methods: {
hi(){
console.log("hi");
}
}
}).$mount("#app");
传递进来的el
是<button>点我</button>
,就是HTML的信息
传递进来的info
就包含click
,存在info
的arg
里面,那么我们就可以判断是不是click
就可以了,info.value
就是hi
,就可以调用这个方法。
就是实现了模仿一个v-on
,
指令的作用
主要用于DOM操作
- Vue实例/组件用域数据绑定,事件监听,DOM更新
- Vue指令主要目的就是原生DOm操作
减少重复
- 如果某个DOM操作你经常使用,就可以封装为指令
- 如果某个DOM操作比较复杂,也可以封装为指令
如果不使用指令,
<div id="hi"></div>
给div绑定点击事件,不使用指令的话
created(){
this.$el.querySelector('#h1').addEventListener('click', ()=>console.log('x'))
}
是用钩子函数来绑定点击事件,但是删除事件比较麻烦,v-on
自己把这些都做好了,包括删除事件绑定(当HTML元素消失的时候)。
指令就减少了DOM操作。