Vue3中自定义指令 - 钩子函数 官网
自定义指令有多个钩子函数,如mounted、updated等。mounted在元素挂载到DOM后调用,updated在组件更新时调用。 app.directive('highlight', { mounted(el) { el.style.backgroundColor = 'yellow'; }, updated(el) { el.style.backgroundColor = 'green'; }}); // 运行结果:元素挂载时背景为黄色,组件更新时背景变为绿色 不同钩子函数在不同时机执行,使用时要注意。