Eugene Karataev
Eugene Karataev

Reputation: 1971

Vue router and component lifecycle hooks

I've faced counter-intuitive vue router behavior and want to know what I'm missing.

Here's a code for demonstration

// 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>

When navigating from the first page to second I expect logs like

first created / 
first destroyed /
second created /second 

But instead I get

first created / 
second created /second 
first destroyed /second 

Codesandbox

I.e. second page component is created BEFORE the first one is destroyed. So the first component in destroyed hook has access to the another $route, which is wrong in my opinion. Why does it happen this way? Thanks in advance!

Upvotes: 2

Views: 1586

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

This behavior is generated because the component lifecycle hooks are merged with the In-Component Guards from the router :

first component :

  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);
  },
 

second component :

 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);
  },
  

Upvotes: 1

Related Questions