通过key决定是否刷新keep-alive组件的方法


有时候不一定需要exclude去控制哪些组件要被排除在缓存外面的,有些可能是根据实际情况决定是否控制缓存,这时候网上有

 

<keep-alive v-if='$route.meta.keepAlive">
<router-view ></router-view>
</keep-alive>
 
就是通过路由配置meta去实现的,但是本人测试了一下以后发现其实是不可以做到的,这时候可以换个思路,使用key 刷新router-view去实现控件刷新,大概代码如下:
HTML:
 <keep-alive>
            <router-view :key="checkKeepAlive()"></router-view>
          </keep-alive>

JS:

checkKeepAlive() {
      if (!this.$route.meta.keepAlive) {
        console.log('输出',this.$route.name)
        return this.$route.name+Math.random();
      }
    }

router:(我这里是自路由控制)

 children: [
      {
        path: "/home/test1",
        name: "test1",
        meta: {
          keepAlive: true
        },
        component: () => import("@/components/Test1.vue")
      },
      {
        path: "/home/test2",
        name: "test2",
        meta: {
          keepAlive: false
        },
        component: () => import("@/components/Test2.vue")
      }
    ]

然后你就可以写JS去控制keepalive的true/false去实现缓存可控了

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM