【问题标题】:Is there any solution for tricking vue's lifecycle hook order of execution?有没有办法欺骗 vue 的生命周期钩子执行顺序?
【发布时间】:2020-01-22 16:09:51
【问题描述】:

被销毁的钩子比我需要的要晚。

我尝试使用 beforeDestroy 而不是 destroy,mounted hook 而不是 created。先前组件的destroy hook总是在替换它的组件的created hook之后调用。

App.vue

  <div id="app">
    <component :is="currentComponent"></component>
    <button @click="toggleComponent">Toggle component</button>
  </div>
</template>
<script>
import A from './components/A.vue';
import B from './components/B.vue';

export default {
  components: {
    A,
    B
  },
  data: function(){
    return {
      currentComponent: 'A'
    }
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'A' ? 'B' : 'A';
    }
  }
}
</script>

A.vue

<script>
export default {
    created: function() {
        shortcut.add('Enter', () => {
            console.log('Enter pressed from A');
        })
    },
    destroyed: function() {
        shortcut.remove('Enter');
    }
}
</script>

B.vue

<script>
export default {
    created: function() {
        shortcut.add('Enter', () => {
            console.log('Enter pressed from B');
        })
    },
    destroyed: function() {
        shortcut.remove('Enter');
    }
}
</script>

结果:

// Click Enter
Enter pressed from A
// now click on toggle component button
// Click Enter again
Enter pressed from A

预计在第二次输入后显示我从 B 按下 Enter。

请不要向我展示 vue 生命周期的图表,我已经意识到这一点,我只需要针对这种特定情况的解决方法。 不接受使用 setTimeout 之类的愚蠢答案。

编辑:对代码和描述进行了一些更改

【问题讨论】:

  • 这个问题没有建设性。它很有可能只能得到“愚蠢”的答案。您可能有需要以另一种方式解决的 XY 问题。考虑解释您的情况,以便建议适当的解决方法。

标签: vue.js vuejs2


【解决方案1】:

如果您使用vue-router,您可以在您拥有beforeRouteLeave 的组件(以及路由器文件)中使用路由器防护,显然仅在路由发生变化时才有效,请参见此处: https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2019-11-27
    • 2020-02-17
    • 2021-03-26
    • 1970-01-01
    • 2019-10-04
    • 2017-11-28
    相关资源
    最近更新 更多