vue中监听路由和路由参数的变化

本文探讨了如何在Vue应用中解决路由参数变更不触发生命周期方法的问题,通过监听$route对象和参数变动来确保数据同步。

问题描述

在同一个路由下,只改变路由后面的参数值 / 改变路由,比如 /test?id=1 ,在这个页面中点击一个按钮后 跳转到 /test?id=2 ,但从“/test?id=1”到“ /test?id=2”是不会触发vue的生命周期的,id变了,但页面数据不会更新。

解决办法

监听路由参数的变化,在watch里监听$route和路由参数

watch: {
  $route(){   
   this.userId= this.$route.query.id
  },
 }
Vue项目中,不同版本监听路由参数变化并重新加载页面的方法有所不同。 ### Vue 2.x 在Vue 2项目里,可在组件中使用`watch`来监听`$route`对象的变化,当路由参数改变时,可调用`this.$router.go(0)`来重新加载页面。示例代码如下: ```vue <template> <!-- 组件模板 --> <div> <!-- 页面内容 --> </div> </template> <script> export default { watch: { '$route': { handler(newRoute, oldRoute) { // 当路由参数变化时重新加载页面 this.$router.go(0); }, deep: true } } } </script> ``` 也可以在全局路由守卫里监听路由变化,示例如下: ```javascript import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { if (to.path === from.path && JSON.stringify(to.query) !== JSON.stringify(from.query)) { // 路由路径相同但参数不同,重新加载页面 window.location.reload(); } next(); }); new Vue({ router }).$mount('#app') ``` ### Vue 3.x 在Vue 3项目中,可使用`watch`函数来监听`router.currentRoute.value`的变化。当路由参数改变时,同样可以使用`window.location.reload()`来重新加载页面。示例代码如下: ```vue <template> <!-- 组件模板 --> <div> <!-- 页面内容 --> </div> </template> <script setup> import { watch } from 'vue'; import { useRouter, useRoute } from 'vue-router'; const router = useRouter(); const route = useRoute(); watch( () => route.fullPath, (newPath, oldPath) => { // 当路由参数变化时重新加载页面 window.location.reload(); }, { immediate: false, deep: true } ); </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值