router.js代码
const routes = [
{
path: "/",
name: "Home",
component: Home,
children: [
{
path: "/about",
name: "About",
component: () =>
import( "../views/About.vue"),
},
{
path: "/other",
name: "Other",
component: () =>
import("../views/Other.vue"),
}
],
},
];
about.vue代码和other代码差不多就是名字改了
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script>
export default {
data() {
return {};
},
watch:{
$route:function(to,from){
console.log('about路由变化',to,from);
}
}
};
</script>
home.vue代码
<template>
<div id="nav">
<router-link :to="{path:'/about',query:{id:'123'}}">About</router-link>
<router-link to="/other">Other</router-link>
<router-view/>
</div>
</template>
<script>
export default {
name: 'Home',
watch:{
$route(){
console.log('home路由变化');
}
}
}
</script>
运行结果及报错内容
点两个按钮去切换about和other路由无法输出是相应的路由变化,只会输出 home路由的变化
我想要达到的结果
在进入相应的页面的时候通过watch能监听到相应的路由变化 ,比如进入about会输出我上面写的about路由变化。就用watch监听
$route,不用组件内守卫