自定义指令:常用于封装一些 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>