【问题标题】:Vue router and component lifecycle hooksVue 路由器和组件生命周期钩子
【发布时间】: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,在我看来这是错误的。为什么会这样?提前致谢!

【问题讨论】:

    标签: vue.js vue-router


    【解决方案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);
      },
      
    

    【讨论】:

      猜你喜欢
      • 2015-12-08
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2020-03-15
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多