Vue 自定义指令 (Custom Directives) - Vue 2 和 Vue 3

141 阅读1分钟

Vue 允许你注册自定义指令,这样可以让你创建可重用的代码来处理一些常见的 DOM 操作。下面是 Vue 2 和 Vue 3 中自定义指令的介绍和使用语法。

Vue 2

介绍

在 Vue 2 中,你可以创建自定义指令来执行你想要的任何 DOM 操作。

注册全局自定义指令

Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})

注册局部自定义指令

new Vue({
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  }
})

使用自定义指令

<input v-focus>

Vue 3

介绍

在 Vue 3 中,自定义指令的 API 有所改变,但基本概念保持不变。

注册全局自定义指令

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

注册局部自定义指令

export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus()
      }
    }
  }
}

使用自定义指令

<input v-focus>

指令钩子函数

自定义指令有几个钩子函数,你可以使用它们来执行你想要的操作:

  • bind (Vue 2) / beforeMount (Vue 3): 只调用一次,指令第一次绑定到元素时调用。
  • inserted (Vue 2) / mounted (Vue 3): 被绑定元素插入父节点时调用。
  • update (Vue 2) / beforeUpdate (Vue 3): 所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。
  • componentUpdated (Vue 2) / updated (Vue 3): 指令所在组件的 VNode 及其子 VNode 全部更新后调用。
  • unbind (Vue 2) / beforeUnmount (Vue 3): 只调用一次,指令与元素解绑时调用。

希望这能帮到你!如果你有任何其他问题或需要进一步的澄清,请继续提问。