Vue 3 自定义指令写法:生命周期钩子与注册方式

作者:云间搭桥

时间:2026-12-04

浏览:667

在 Vue 3 中,自定义指令需通过 app.directive 注册,其生命周期钩子从 bind 、 inserted 、 update 、 componentUpdated 、 unbind 调整为 beforeMount 、 mounted 、 beforeUpdate 、 updated 、 beforeUnm

文章目录

在 Vue 3 中,自定义指令需通过 app.directive 注册,其生命周期钩子从 bind、inserted、update、componentUpdated、unbind 调整为 beforeMount、mounted、beforeUpdate、updated、beforeUnmount、unmounted。实现时直接导出包含这些钩子的对象即可。

Vue 3 自定义指令写法:生命周期钩子与注册方式

Vue 2 与 Vue 3 指令钩子映射关系

Vue 3 重构了响应式系统并引入 Composition API,指令系统的钩子命名也随之改变以更好地反映 DOM 生命周期。旧版的 bind 和 inserted 合并为 beforeMount(元素插入父节点前)和 mounted(元素插入后),而 update 系列则对应组件的更新周期。理解这种映射是迁移或编写兼容代码的关键。

Vue 3 自定义指令写法:生命周期钩子与注册方式

在 Vue 2 中,bind 仅在指令第一次绑定到元素时调用,用于一次性初始化设置;inserted 则在元素被插入父节点时调用,适合操作 DOM 布局。Vue 3 中,beforeMount 承担了 bind 的职责,但此时元素尚未挂载到真实 DOM,因此若需操作 DOM 属性或样式,应使用 mounted。beforeUpdate 和 updated 分别对应数据变化前后,替代了旧的 update 和 componentUpdated。这种调整使得指令行为更贴合组件的生命周期,减少了歧义。

完整指令实现与注册方式

以下代码展示了一个完整的 Vue 3 自定义指令实现,包含所有生命周期钩子,并通过 app.directive 进行全局注册。该指令用于聚焦输入框并添加高亮边框,演示了如何在不同阶段操作 DOM 元素。

Vue 3 自定义指令写法:生命周期钩子与注册方式

// focusDirective.js
export const focusDirective = {
  beforeMount(el, binding, vnode) {
    console.log('beforeMount: 元素即将挂载');
    el.style.border = '2px solid green';
  },
  mounted(el, binding, vnode) {
    console.log('mounted: 元素已挂载');
    el.focus();
  },
  beforeUpdate(el, binding, vnode) {
    console.log('beforeUpdate: 组件即将更新');
    el.style.borderColor = 'blue';
  },
  updated(el, binding, vnode) {
    console.log('updated: 组件已更新');
    el.style.borderColor = 'green';
  },
  beforeUnmount(el, binding, vnode) {
    console.log('beforeUnmount: 元素即将卸载');
  },
  unmounted(el, binding, vnode) {
    console.log('unmounted: 元素已卸载');
  }
};

程序输出显示各钩子按顺序触发:先 beforeMount 设置绿色边框,再 mounted 聚焦输入框。当绑定值变化时,beforeUpdate 将边框变蓝,updated 恢复绿色。卸载时依次触发 beforeUnmount 和 unmounted。若发现边框未变色,检查是否误用了 Vue 2 的 update 钩子名,Vue 3 必须使用 beforeUpdate 和 updated。

将上述代码保存为 focusDirective.js,并在 Vue 应用入口文件中通过 import { createApp } from 'vue' 和 app.directive('focus', focusDirective) 注册。运行后,页面加载时输入框自动获得焦点并显示绿色边框;当修改绑定的值时,边框颜色会短暂变为蓝色再恢复,体现 beforeUpdate 和 updated 的效果。移除元素时,控制台会打印卸载日志。

参数变化时的 updated 钩子触发条件

updated 钩子在指令所在组件的 VNode 及其子 VNode 全部更新后调用。这意味着它发生在 DOM 已更新之后,适合执行需要依赖最新 DOM 状态的操作。

在示例程序中,当绑定的值发生变化时,beforeUpdate 会在 DOM 更新前触发,可用于准备状态;updated 则在 DOM 更新后触发,确保能读取到最新的元素属性。若指令逻辑依赖于父组件或其他兄弟组件的状态变化,需注意 updated 并非仅由自身绑定值变化触发,而是整个组件树更新的结果。因此,在复杂场景中,建议结合 v-once 或计算属性减少不必要的更新触发。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章