1. keep-alive缓存组件的作用

使用vue开发时:有ABC页面,A跳转B,B跳转C,C返回跳转B,B返回跳转A

但是:可能会出下这个问题:从A-B-C正常,但当从B返回A时,会报错,这是因为从B返回A时,传递的参数并不是从A到B的参数

所以:需要将B组件或页面缓存起来,就可以解决这个问题,缓存可以用vue 中的keep-alive标签,使用方法如下:

 加上判断条件,如果keepAlive为true,那么就缓存该组件,也就是用keep-alive包裹它
如果为false,那么就不包裹

    <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>

通过设置keepAlive的true或false来决定该组件是否缓存

const routes = [
  {
    path: "/",
    name: "A",
    component: () => import("@/views"),
    meta: {
      keepAlive: false,
    },
  },
  {
    path: "/B",
    name: "B",
    component: () => import("@/views/B"),
    meta: {
      keepAlive: true,
    },
  },
]

  2. keep-alive清除缓存组件的作用

B跳转A页面是,直接清除缓存,则让A页面强制刷新

监听路由跳转,但监听到跳往的页面是A页时,直接刷新


      <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>

``````````````````````````````````````````````````````

watch: {
  $route(to, from) {
   if (to.name === "B" && from.name) {
     this.$router.go(0); // 刷新该页面
    }
  }
}

 

Logo

前往低代码交流专区

更多推荐