vue keep-alive不生效

理论上说,Vue的页面缓存提供了组件keep-alive,应该很简单,但实际开发中遇到alive失效的问题。
初始代码,如下:

<keep-alive :include="includePageNames">
  <router-view class="router_container" :key="$key()" />
keep-alive>

// 或者(并没真实试验以下方式是否可以,参考资料有这种写法)
<keep-alive >
  <router-view v-if="$route.meta.keepAlive" class="router_container" :key="$key()" />
keep-alive>
<router-view v-if="!$route.meta.keepAlive" class="router_container" :key="$key()" />
watch: {
 '$route' : {// 监听路由,取值
   handler(nv, ov) {
     this.headShow = nv.path !== '/person';
     this.bottomShow = nv.path !== '/report/detail';

     for(let i in nv.matched){
       if(i !== 0){
         let indexOf = this.includePageNames.indexOf(nv.matched[i].name)
         //判断数组中是否存在这个name,如果存在,则说明是返回的,要清除缓存
         if(indexOf === -1 && nv.matched[i].meta.keepAlive) {//不存在,添加缓存
           this.includePageNames.push(nv.matched[i].name)
         }
       }
     }
   },
   deep: true,
   immediate: true
 }
},

折腾了很久,终于找到问题节点,是router-view标签上的key属性引起的,$key()每次都会产生一个动态数值,因此解析时会认为进入了一个新页面,造成了页面刷新和数据重载。
调整如下即可:

<keep-alive :include="includePageNames">
  <router-view class="router_container" :key="key" />
keep-alive>

// 或者(并没真实试验以下方式是否可以,参考资料有这种写法)
<keep-alive >
  <router-view v-if="$route.meta.keepAlive" class="router_container" :key="key" />
keep-alive>
<router-view v-if="!$route.meta.keepAlive" class="router_container" :key="key" />
computed: {
  key() {
    // return this.$key();
    return this.$route.path
  }
},

你可能感兴趣的:(Vue,vue)