目录?前言?一、自定义指令分类?二、Vue2.x自定义指令钩子函数(1)bind与update区别(2)update与componentUpdated区别(3)钩子函数的参
vue自定义指令(2.x丨3.x)可以帮助我们实现需要操作,比如防抖、节流、懒加载、输入框自动聚焦等等,使用起来非常方便,比如vue自带的v-text、v-html、v-show、v-if等等。
相同点:
异同点:
Vue.directive('focus', {
inserted: function (el) {
console.log(el.parentNode, 'inserted')
el.focus();
},
bind: function (el) {
console.log(el.parentNode, 'bind')
el.focus();
},
});
输出结果如下,说明执行bind时,还没父节点;执行inserted时,已有父节点。
<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";
}
},
},
使用Vue.directive(‘指令名称’,{钩子函数})
Vue.directive('style',{
bind(el) {
el.style.fontSize = "30px";
el.style.color = "blue";
},
},
)
如果update逻辑与bind相同的话可以直接把指令当成函数写
Vue.directive('style',{
bind(el) {
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>
组件A.vue
<input type="text" v-focus>
在directives文件夹新建focus.ts文件
const directives: any = {
mounted(el: any) {
el.focus();
el.value = '1'
}
}
export default {
name: "focus",
directives
}
在directives文件夹新建index.js
import type { App } from 'vue'
import focus from './focus'
export default function installDirective(app: App) {
app.directive(focus.name, focus.directives);
}
main.ts文件
import directives from './directives'
const app = createApp(App);
app.use(directives);
当update和mounted中的函数体一样时,则可以简写成如下:
const directives = (el:any) => {
el.focus();
el.value = '1';
}
export default {
name: "focus",
directives
}
到此这篇关于vue2.x与vue3.x中自定义指令详解的文章就介绍到这了,更多相关vue2.x与vue3.x自定义指令内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: vue2.x与vue3.x中自定义指令详解(最新推荐)
本文链接: https://www.lsjlt.com/news/174330.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0