chaihongjun.me

Vue路由跳转组件生命周期变化

结合前面一篇《Vue中父子组件的生命周期》,这篇总结一下页面组件切换适合的生命周期变化。

创建另外一个子组件


About.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
  </div></template><script>export default {
  name: "About",
  beforeCreate() {
    console.log("About beforeCreate", this.$data, this.$el);
  },
  created() {
    console.log("About created", this.$data, this.$el);
  },
  beforeMount() {
    console.log("About beforeMount", this.$data, this.$el);
  },
  mounted() {
    console.log("About mounted", this.$data, this.$el);
  },
  beforeUpdate() {
    console.log("About beforeUpdate", this.$data, this.$el);
  },
  updated() {
    console.log("About updated", this.$data, this.$el);
  },
  beforeUnmount() {
    console.log("About beforeUnmount", this.$data, this.$el);
  },
  unmounted() {
    console.log("About unmounted", this.$data, this.$el);
  },};</script>

这个时候的组件结构是

<App>
    <Home>
         <HelloWorld>
    <About>

home组件有子组件HelloWorld,有兄弟组件About。

首先页面加载,控制台显示:

QQ截图20210922112801.png

子组件的生命周期在父组件mounted之前完成。


接着点击导航进入about,控制台完整显示:

QQ截图20210922112840.png

红色框部分是点击导航之后新增加的,注意黄色框和其他的差异。可以总结几条:

  1. 因为是从home导航至about,所以肯定是home先挥手告别(beforeUnmount),但是还没有真的离开,所以没有继续(unmounted)

  2. 由于Home包含子组件,所以子组件也跟随挥手告别(beforeUnmount)

  3. 既然是挥手告别home组件,那么去向About组件应该是需要准备好,于是就有了about相应的生命周期(beforeCreate,created,beforeUnmount)

  4. 这时About组件不能马上(mounted),因为前面还只是挥手告别而已(beforeUnmount)

  5. 接着才是从Home和它子组件的离开(unmounted),这里父子组件的卸载也有逻辑顺序,一定是子组件都卸载了,才轮到父组件卸载

  6. 最后是目的组件的挂载完成(mounted)


当然,也可以从另外角度解释,当从一个组件跳到另外一个组件的时候,前一个组件要进入到先准备卸载(beforeUnmount),接着后一个组件从创建到进入到准备挂载(beforeCreated->beforeMount),最后,前一个组件正式卸载(unmounted),后一个组件正式挂载(mounted).如果遇到前一个组件包含有子组件,那么准备卸载一定是父组件先带头,正式卸载则是子组件先执行。

知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:chaihongjun»