Vue (H5)跳转到新页面再返回到旧页面保持状态不变(keep-alive)

新项目中遇到了A页面跳转到B页面用户填写并收集数据相关数据成功返回到A页面时,A页面被重置刷新,所有已经填写的其他数据均没了的问题,为了解决这个问题,我们不得不使用以下方案解决问题:

页面路由如下:

A页面:path: '/home',

B页面:path: '/info',

解决方案:使用keep-alive

  1. 在vue.app中添加keep-alive标签。
//App.vue
<template>
  <div id="app">
     <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
     </keep-alive>
      <router-view v-if="!$route.meta.keepAlive" />
  </div>
</template>

<script>
export default {};
</script>

     2.在router文件下的index.js中,添加meta节点并新增keepAlive:true

//router/index.js
export const constantRoutes = [
  {
    path: "/",
    redirect: '/home',
    component: () => import("@/views/home.vue"),
  },
  {
    path: "/home",
    component: () => import("@/views/home.vue"),
    meta: { keepAlive: true }
  },
  {
    path: "/info",
    component: () => import("@/views/info.vue"),
    meta: { keepAlive: true }
  },
];

   3.在B页面(/info)中添加:

//info.vue
beforeRouteLeave(to,form,next){
    to.meta.keepAlive = true;
    next(0)
  },

搞定~

 

 --End--

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值