Vue 的自定义指令中何时调用 bind 和 unbind 以及它们如何与生命周期函数(挂载/销毁)相关联

use*_*238 5 javascript vue.js vuejs2

说,我创建了一个自定义指令来处理窗口调整大小事件,我写了

Vue.directive('resize', {
  bind(el, binding, vnode) {
    el.resizeEvent = function() {
      vnode.context[binding.expression]()
    }

    // I would like it to be called in mounted
    Vue.nextTick(el.resizeEvent)

    window.addEventListener('resize', el.resizeEvent)
  },
  unbind(el) {
    window.removeEventListener('resize', el.resizeEvent)
  }
})
Run Code Online (Sandbox Code Playgroud)

我添加Vue.nextTick(el.resizeEvent)是因为我希望在安装组件时调用此函数。

到目前为止,该指令按预期工作。不过,我没有约时,一个清晰的思路bindunbind被调用。

该文件声称

bind: called only once, when the directive is first bound to the element. This is where you can do one-time setup work.

unbind: called only once, when the directive is unbound from the element.

我的问题是,当正好是bindunbind所谓的,他们如何与生命周期挂钩,例如mountedcreateddestroyed

小智 1

在 nuxt 应用程序上运行一些测试。这是我的结果:

  1. 已创建
  2. 绑定
  3. 安装的

  1. 销毁前
  2. 被摧毁
  3. 解除绑定

我没有测试更新挂钩。