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