自定义指令:常用于封装一些 DOM 操作,提高代码的复用性
语法格式:
// 完整写法
const 指令名 = {
mounted: (el, binding) => {},
updated: (el, binding) => {}
}
// 简写
const 指令名 = (el, binding) => {}
// 选项式写法
export default {
......
directives: {
// 完整写法
big: {
mounted: (el, binding) => {},
updated: (el, binding) => {}
},
// 简写
bigs(el, binding) {}
}
}
自定义指令【完整写法】:
<template>
<p>当前的num值是:<span v-text="num"></span></p>
<p>放大10倍的num值是:<span v-big="num"></span></p>
<button @click="num++">点击num+1</button>
</template>
<script setup>
import { ref } from "vue";
let num = ref(1);
// 创建自定义指令
const vBig = {
// 绑定的元素挂载时执行
mounted: (el, binding) => {
console.log(el); // 绑定指令的 DOM 元素
console.log(binding); // 绑定指令的对象
el.innerText = binding.value * 10;
},
// 绑定的值更新时执行
updated: (el, binding) => {
console.log(el); // 绑定指令的 DOM 元素
console.log(binding); // 绑定指令的对象
el.innerText = binding.value * 10;
}
}
</script>

自定义指令【简写】:
<template>
<p>当前的num值是:<span v-text="num"></span></p>
<p>放大10倍的num值是:<span v-big="num"></span></p>
<button @click="num++">点击num+1</button>
</template>
<script setup>
import { ref } from "vue";
let num = ref(1);
// 简写:在 mounted 和 updated 时执行
const vBig = (el, binding) => {
console.log(el); // 绑定指令的 DOM 元素
console.log(binding); // 绑定指令的对象
el.innerText = binding.value * 10;
}
</script>

原创作者:吴小糖
创作时间:2024.2.27
本文详细介绍了如何在Vue中使用自定义指令封装DOM操作,包括完整写法、简写形式,以及mounted和updated钩子的使用,提升代码复用性。
1293

被折叠的 条评论
为什么被折叠?



