自定义指令

    下面是对变更的简要总结:

    • API 已重命名,以便更好地与组件生命周期保持一致
    • 自定义指令将由子组件通过

    更多信息,请继续阅读!

    在 Vue 2,自定义指令是通过使用下面列出的钩子来创建的,这些钩子都是可选的

    • bind - 指令绑定到元素后发生。只发生一次。
    • inserted - 元素插入父 DOM 后发生。
    • update - 当元素更新,但子元素尚未更新时,将调用此钩子。
    • componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。
    • unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。

    下面是一个例子:

    1. Vue.directive('highlight', {
    2. bind(el, binding, vnode) {
    3. el.style.background = binding.value
    4. })

    在这里,在这个元素的初始设置中,指令通过传递一个值来绑定样式,该值可以通过应用程序更新为不同的值。

    • bind → beforeMount
    • inserted → mounted
    • beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子。
    • update → 移除!有太多的相似之处要更新,所以这是多余的,请改用 updated
    • componentUpdated → updated
    • beforeUnmount:新的!与组件生命周期钩子类似,它将在卸载元素之前调用。
    • unbind -> unmounted

    最终 API 如下:

    1. const MyDirective = {
    2. beforeMount(el, binding, vnode, prevVnode) {},
    3. mounted() {},
    4. beforeUpdate() {},
    5. updated() {},
    6. unmounted() {}

    生成的 API 可以这样使用,与前面的示例相同:

    1. const app = Vue.createApp({})
    2. app.directive('highlight', {
    3. beforeMount(el, binding, vnode) {
    4. el.style.background = binding.value
    5. }
    6. })

    既然定制指令生命周期钩子映射了组件本身的那些,那么它们就更容易推理和记住了!

    It’s generally recommended to keep directives independent of the component instance they are used in. Accessing the instance from within a custom directive is often a sign that the directive should rather be a component itself. However, there are situations where this actually makes sense.

    In Vue 2, the component instance had to be accessed through the vnode argument:

    1. bind(el, binding, vnode) {
    2. }

    在 Vue 3 中,我们现在支持片段,这允许我们为每个组件返回多个 DOM 节点。你可以想象,对于具有多个 <li> 的组件或一个表的子元素这样的组件有多方便:

    1. <template>
    2. <li>Hello</li>
    3. <li>Vue</li>
    4. <li>Devs!</li>
    5. </template>

    如此灵活,我们可能会遇到一个定制指令的问题,它可能有多个根节点。

    因此,自定义指令现在作为虚拟 DOM 节点数据的一部分包含在内。当在组件上使用自定义指令时,钩子作为无关的 prop 传递到组件,并以 this.$attrs 结束。

    这也意味着可以像这样在模板中直接挂接到元素的生命周期中,这在涉及到自定义指令时非常方便:

      这与属性 fallthrough 行为是一致的,因此,当子组件在内部元素上使用 v-bind="$attrs" 时,它也将应用对其使用的任何自定义指令。