小白都能看懂,只需4步,解决vue keep-alive缓存组件问题

11,015 阅读1分钟

1.首先在路由中配置需要缓存组件的标识:(keepAlive: true),尝试过先设置为false,然后在路由守卫里通过判断条件设置为true,但是遇到第一次不生效,第二次才生效的问题

export default [
  {
    path: '/',
    component: () =>
      import(
        /* webpackChunkName: "mainContainer" */ '@/views/mainContainer/index.vue'
      ),
    children: [
      {
        path: 'list',
        meta: {
          keepAlive: true,
        },
        component: () =>
          import(
            /* webpackChunkName: "resource" */ '@/views/index.vue'
          ),
      },
    ],
  },
]

2.在App.vue中添加相关代码

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

3.在缓存的组件中使用activated生命周期钩子函数,当组件在 keep-alive 内被切换时activated被激活,简单来讲就是在什么情况下需要请求数据,什么时候直接使用缓存的数据

activated() {
    console.log('没错我在缓存组件中')
  },

4. 业务场景,现在有A,B,C三个页面,在B页面做一些操作,比如说通过输入搜索条件搜出相关的数据,然后点击一条数据,跳转到详情页C,在C页面点击返回按钮,B还保持搜索后的状态,除此之外A跳到B不需要缓存组件,始终是最新的数据状态,此时可以通过添加一个type来区分

c页面点击返回按钮,返回到B
 this.$router.push({path:'b?type=needToKeep'})  /* needToKeep是需要使用缓存的标识*/
 
 A页面到B页面,
 this.$router.push({path:'b'})
 
 B页面中:
 activated() {
    const { type } = this.$route.query
    console.log('没错我在缓存组件中')
    if(type !=='needToKeep'){
      this.initdata() // 需要重新请求数据
    }else{
     // 直接使用缓存的组件,假如说此时想刷新页面,重新请求数据怎么办呢,安排!
     const { type } = window.performance.navigation  // 1:刷新页面,0:返回页面
     type === 1 ? this.initdata() : '' 
    }
 },

总结:keep-alive是比较方便的一个功能,用法也比较简单,但结合业务场景,别人的解决方案可能并不太适合,多多少少会遇到一点问题,所以找到适合自己业务的解决方案才是最好的