Vue 中使用watch监听$route失效问题!
今天在项目操作中发现一个问题,在watch里面监听$route变化,发现并没有监听到,查阅了一些资料最终解决,现写出与大家共同分享,也忘出现此问题的同学也能顺利解决
路由词典:
{name: 'secondUser ',component: secondUser,path: '/secondUser',
}
-------------------------------------------------------------------------------------------------------------------
页面中监听watch:{'$route'(to,from) { console.log(to,from);}},
结果我们发现在路由跳转后,我们的console并没有输出东西,加了断点发现也并没有执行到里面,原来,我们用watch监听路由变化,我们的路由一定要有子路由,监听变化也紧局限在父子路由中,也就是我们这个路由一定要有子路由,在子路由跳转过程中会调用watch,能成功监听!
我们为secondUser路由增加了两个子路由!
-------------------------------------------------------------------------------------------------------------------
我们发现在进行父子路由跳转过程中,我们的watch可以坚挺到路由变化了!
--------------------------------------------------------
{name: 'secondUser ',component: secondUser,path: '/secondUser',children: [{path: 'user',name: 'user',component: user,},{path: 'userName',name: 'userName',component: userName,},]},
watch监听$route在平级路由子组件中失效
{path: '/index_1',name: 'Index_1',component: () => import('@/views/index_1.vue'),meta: {title: '首页_1',requireAuth: true},children: [{path: '/index_1/sub_index_A',name: 'sub_index_A',component: () => import('@/views/sub_index_1/sub_index_A.vue'),meta: {title: '子组件_A',requireAuth: true}},{path: 'sub_index_B',name: 'sub_index_B',component: () => import('@/views/sub_index_1/sub_index_B.vue'),meta: {title: '自组件_B',requireAuth: true}},{path: 'sub_index_C',name: 'sub_index_C',component: () => import('@/views/sub_index_1/sub_index_C.vue'),meta: {title: '自组件_C',requireAuth: true}}]}
如上路由配置 watch 在子组件sub_index_A、sub_index_B、sub_index_A中监听$route无效