vue中可以通过directive创建自定义的指令,
可全局定义,也可局部
局部:
const vm = new Vue({
el:"#app",
data: {
a: 10,
money: 1000000
},
directives:{ // 局部自定义指令
slice: (el, bindings, vnode)=>{
console.log(el);
console.log(bindings);
console.log(vnode);
}
}
});
directive中的钩子函数:
- bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
- inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
- update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 。
- componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
- unbind:只调用一次,指令与元素解绑时调用。
钩子函数的参数:
- 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 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
- oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
<body>
<div id="app">
<input type="text" v-slice:9.number="content">
{{content}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 函数的方式
// Vue.directive('slice',(el, bindings, vnode)=>{
// console.log(el);
// console.log(bindings);
// console.log(vnode);
// const val = bindings.value.slice(0, 5);
// vnode.context.content = val;
// console.log(bindings.def);//bindings 和 update
// })
// 对象的方式
Vue.directive('slice',{
bind(el, bindings, vnode){ //只执行第一次
const context = vnode.context;
el.value = context[bindings.expression];
const length = bindings.arg || 5;
// 修饰符
const numberFlag = bindings.modifiers.number;
let initVal = context[bindings.expression];
if(numberFlag){
initVal = initVal.replace(/[^0-9]/g, "");
}
initVal = initVal.slice(0, length);
el.value = initVal;
context[bindings.expression] = initVal;
el.oninput = e=>{
let value = e.target.value;
if(numberFlag){
value = value.replace(/[^0-9]/g, "");
}
let val = value.slice(0,length);
context[bindings.expression] = val;
el.value = val;
}
},
updata(el, bindings, vnode){ //第一次不会执行
// 虚拟节点更新时操作
let context = vnode.context;
const numberFlag = bindings.modifiers.number;
let value = context[bindings.expression];
if(numberFlag){
value = value.replace(/[^0-9]/g, "");
}
el.value = value;
},
inserted (el){
// 当元素插入之后执行
// 第一次进入界面时聚焦
el.focus();
}
})
var vm = new Vue({
el: "#app",
data: {
content: 'jk1242jkjldfshfl'
}
});
</script>
</body>