如何写一个 Vue 自定义指令(directive)?常用钩子有哪些?

指令是复用 DOM 底层行为的手段(如自动聚焦、权限控制、懒加载)。

app.directive('focus', {
  mounted(el) { el.focus() },          // 绑定元素插入父节点后
  updated(el, binding) { /* 组件更新后 */ },
  unmounted(el) { /* 解绑 */ }
})
// 使用:<input v-focus />

钩子:created / beforeMount / mounted / beforeUpdate / updated / beforeUnmount / unmounted。binding 含 value、arg、modifiers 等。

何时用指令 vs 组件:涉及普通 DOM 操作用指令;涉及结构/状态用组件。Vue3 中多数场景更推荐 composable。

同分类其他题目