Vue 路由器和组件生命周期钩子

Posted

技术标签:

【中文标题】Vue 路由器和组件生命周期钩子【英文标题】:Vue router and component lifecycle hooks 【发布时间】:2021-06-14 17:40:54 【问题描述】:

我遇到了违反直觉的 vue 路由器行为,想知道我错过了什么。

这是演示代码

// main.js
import Vue from "vue";
import Router from "vue-router";
import FirstPage from "@/components/FirstPage";
import SecondPage from "@/components/SecondPage";
import App from "./App.vue";

const routes = [
  
    path: "/",
    component: FirstPage
  ,
  
    path: "/second",
    component: SecondPage
  
];

const router = new Router(
  mode: "history",
  routes
);

Vue.use(Router);

new Vue(
  render: (h) => h(App),
  router
).$mount("#app");


// App.vue
<template>
  <router-view />
</template>

<script>
export default ;
</script>


// FirstPage.vue
<template>
  <div>
    <h1>first page</h1>
    <router-link to="/second">second</router-link>
  </div>
</template>

<script>
export default 
  created() 
    console.log("first created", this.$route.path);
  ,
  destroyed() 
    console.log("first destroyed", this.$route.path);
  ,
;
</script>


// SecondPage.vue
<template>
  <div>
    <h1>second page</h1>
    <router-link to="/">home</router-link>
  </div>
</template>

<script>
export default 
  created() 
    console.log("second created", this.$route.path);
  ,
  destroyed() 
    console.log("second destroyed", this.$route.path);
  ,
;
</script>

当从第一页导航到第二页时,我希望日志像

first created / 
first destroyed /
second created /second 

但是我得到了

first created / 
second created /second 
first destroyed /second 

Codesandbox

即第二个页面组件是在第一个页面组件被销毁之前创建的。所以destroyed钩子中的第一个组件可以访问另一个$route,在我看来这是错误的。为什么会这样?提前致谢!

【问题讨论】:

【参考方案1】:

产生这种行为是因为组件生命周期钩子与来自路由器的组件内防护合并:

第一个组件:

  created() 
    console.log("first created", this.$route.path);
  ,
 beforeRouteLeave(to, from, next) 
    console.log("leaving first");
   // this runs before running the destroyed hook
  ,
  destroyed() 
    console.log("first destroyed", this.$route.path);
  ,
 

第二部分:

 beforeRouteEnter (to, from, next) 
    console.log("creating the  second");
 // this guard creates the second component before running the beforeRouteLeave from 
// the first one which will executed and then the destroyed hook is executed 
   ,
created() 
    console.log("second created", this.$route.path);
  ,
  destroyed() 
    console.log("second destroyed", this.$route.path);
  ,
  

【讨论】:

以上是关于Vue 路由器和组件生命周期钩子的主要内容,如果未能解决你的问题,请参考以下文章

VueRouter和Vue生命周期(钩子函数)

Vue_03 vue的生命周期组件插槽Slot路由Router

Vue-的父组件和子组件生命周期钩子函数执行顺序

Vue——生命周期和钩子函数的一些理解

Vue 的父组件和子组件生命周期钩子执行顺序

vue父组件与子组件生命周期钩子顺序是啥?