vue自定义指令(2.x丨3.x)可以帮助我们实现需要操作,比如防抖、节流、懒加载、输入框自动聚焦等等,使用起来非常方便,比如vue自带的v-text、v-html、v-show、v-if等等。
异同点:
<p v-style:[direction]="connect">Enter connection information to connect</p>
directives: {
style: {
bind(el,binding) {
console.log(binding,'binding')
el.style.fontSize = "30px";
el.style.color = "blue";
},
},
},
在组件A.vue,用自定义指令实现改变文字颜色
<p v-style>文字描述</p>
directives: {
style: {
bind(el,binding) {
el.style.fontSize = "30px";
el.style.color = "blue";
},
update(el,binding){
el.style.fontSize = "30px";
el.style.color = "blue";
}
},
},
style:指令的名称,使用的时候要加前面加个v- bind:只会调用一次,指令 ==<font color=red >第一次</font>== 绑定到元素时会调用 el:是指绑定的这个dom元素本身 binding:获取绑定指令的信息(name:指令名称;rawName:指令全称:value:指定绑定的值) update:元素第一次绑定不会触发,绑定的值发生更新触发,参数与binding是相同的,如果逻辑与bind相同的话可以直接把指令当成函数写,上面的指令是对象类型。 v-style:使用指令改变了元素的样式
使用Vue.directive('指令名称',{钩子函数})
如果update逻辑与bind相同的话可以直接把指令当成函数写
directives: {
style(){
el.style.fontSize = "30px";
el.style.color = "blue";
},
},
const myDirective = {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
created(el, binding, vnode, prevVnode) {
// 下面会介绍各个参数的细节
},
// 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode, prevVnode) {}
}
指令的钩子会传递以下几种参数:
<script lang="ts" setup>
// 局部指令, 变量名为驼峰命名(vFocus = v-focus)
const vFocus = {
mounted: (el:any) => {
el.focus()
console.log(el, '已经自动获得焦点')
}
}
</script>
<script lang="ts">
const vFocus = {
focus: {
mounted(el:any){
el.focus();
console.log(el, "已经自动获得焦点");
}
},
};
export default {
setup() { },
directives: vFocus,
};
</script>
<input type="text" v-focus>
const directives: any = {
mounted(el: any) {
el.focus();
el.value = '1'
}
}
export default {
name: "focus",
directives
}
当update和mounted中的函数体一样时,则可以简写成如下:
const directives = (el:any) => {
el.focus();
el.value = '1';
}
export default {
name: "focus",
directives
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。