从同一组件的方法中调用 Vue JS 生命周期挂钩

Call a VueJS life cycle hook from within a method on the same component

我在 "container" 组件中使用 VueJS 的 mounted 挂钩来获取构建视图的数据。当该容器被销毁时,我使用 beforeDestroydestroyed 生命周期挂钩 "clean up" 组件。

这三个钩子不会在路由更改为相同路由但参数不同时调用。建议的处理方法是监听 watch 中的 $route 变化,如下所示:

watch: {
  '$route' (to, from) {
    this.id = to.params.id
    this.getPageData()
  }
}

但是,我没有从 mountedbeforeDestroydestroyed 复制逻辑,而是希望做这样的事情:

watch: {
  '$route' (to, from) {

    // Manually run lifecycle clean-up hooks
    this.beforeDestroy()
    this.destroyed()

    // Update Id, and run mounted
    this.id = to.params.id
    this.mounted()
  }
}

不幸的是,$vm 上似乎没有暴露钩子。有没有一种我不知道的方法可以做到这一点?我错过了一些明显的东西吗?或者有更好的/首选的方法吗?

您可以将每个生命周期挂钩内的代码提取到组件方法中,然后在两个地方调用该方法。这是一个例子:

mounted: function() {
    this.__mounted();
},

methods: {
    __mounted() {
        //mounted code here
    }
},

watch: {
  '$route' (to, from) {
        this.__mounted();
  }
}