Vue——自定义指令
自定义指令:
指令地址:src / components / instructions / test / index.js
import Vue from "vue";
Vue.directive("test-instructions",{
// 只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
bind(){},
// 被绑定元素插入父节点时调用(仅保证父节点存在,但不一定已被插入文档中)。
inserted(el,binding,vnode,oldVnode){
/*
el:指令所在绑定的元素,可以用来直接操作DOM
binding:一个对象,包含一下属性:
name:指令名,不包含 “ v- ” 前缀。
value:指令的绑定值,例如:v-my-directive="1 + 1"中,绑定为 2 。
oldValue:指令绑定的前一个值,尽在update和componentUpdated钩子中可用。无论值是否改变都可用。
expression:字符串形式的指令表达式。例如:v-my-directive="1 + 1"中,表达式为 "1 + 1"。
arg:传给指令的参数,可选。例如:v-my-directive:foo 中,参数为"foo"。
modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为{foo:true,bar:true}。
vnode:Vue编译生成的虚拟节点。
oldVnode:上一个虚拟节点,尽在 update 和 componentUpdated 钩子中可用。
*/
testFunction(el);
},
// 所在组件的VNode更新时调用,但是可能发生在其子VNode更新之前。指令的值可能发生改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新。
update(){},
// 指令所在主键的VNode及其子VNode全部更新后调用。
componentUpdated(el,binding,vnode,oldVnode){
testFunction(el);
},
// 只调用一次,指令与元素解绑时调用
unbind(){}
})
// 方法
function testFunction(table) {
console.log("传入数据");
console.log(table);
}
注册指令
在main.js中
import "src/components/instructions/test/index"
指令调用
<el-table v-test-instructions :data="tableData">
<el-table-column label="序号" type="index"></el-table-column>
</el-table>

浙公网安备 33010602011771号