vue 路由切换页面再次进入更新数据

一:同一项目中路由的跳转

mounted和created都只能执行一次,尝试监听改变的数据也未起效果,项目中使用了<keep-alive>,所以用activated监听初始函数

 1.需要跳转的页面home.vue:   页面每次跳转时都改变参数,通过获取不同的时间来实现地址如:http://localhost:8080/#/noticeDetail?time=1641284450820

 

 

 2.路由设置为不缓存上次的数据

{
        path: "/noticeDetail",
        name: "noticeDetail",
        component: pages.noticeDetail,
        meta: {
            title: "公告信息",
            code: "noticeDetail",
            noCache:false 
        }
    },

3.跳转目标页面noticeDetail.vue实现监听:

 activated(){ //项目使用了keep-alive,所以用activate监听才会再次刷新数据
     this.init();//初始化页面
 },

 二、从公共框架中跳转到同一个路由,直接用this.$router.push()的话因为是同一个页面会报错,并且页面数据也不更新

 

 

 解决:1.解决页面报错 NavigationDuplicated: Avoided redundant navigation to current location: "/",原因是路由重复。 

          在 router 文件夹下的 index.js 中加入下面代码,解决!

         

 const originalPush = VueRouter.prototype.push
  VueRouter.prototype.push = function push(location) {
        return originalPush.call(this, location).catch(err => err)
   }

 2.解决路由数据不刷新的问题:先判断当前路由是否是重复的路由,如果是的话就删掉重新加载并且再次reload()

 会有一个问题就是页面原先打开的所有的路由都关了  只保留了最后加载的这个路由,目前没找到好的解决办法

         const time = Date.now();
            sessionStorage.setItem('noticeDetail',JSON.stringify(params));
            // 先关闭当前页面再打开解决第二次打不开页面的问题
            if(this.$route.name=="noticeDetail"){
              this.store.delView(this.$route); //前面用inject引入store,所以可以这样写
              this.$router.push({path:'/noticeDetail',query:{time}});
              setTimeout(()=>{
                location.reload();
              },0)
            }else{
              this.$router.push({path:'/noticeDetail',query:{time}});
            }    

 针对第二种的优化方案:

 用watch监听路由,即使是不同项目之间的跳转也可以监听到路由的变化,之后再次调用接口实现页面刷新数据渲染

watch: {
            $route(to) {  // 先关闭当前页面再打开解决第二次打不开页面的问题
              if (this.$route.name=='noticeDetail') { //noticeDetail为当前打开的这个页面的路由
                // console.log("进来panduan");
                this.init();//后续业务逻辑处理
              }
            }
        },

  



 

posted @ 2022-01-04 16:27  世界我快乐  阅读(4436)  评论(0编辑  收藏  举报