vue路由在keep-alive下的刷新问题

问题描述:

  在keep-alive中的在跳转到指定的路由时刷新对应的路由,其余不刷新。

<transition name="fade" mode="out-in">
   <keep-alive>
       <router-view></router-view>
   </keep-alive>
</transition>

有几种解决方式:

  1.在keep-alive中直接添加 include,cachedViews(Array类型:包含vue文件的组件name都将被缓存起来);反之exclude则是不包含;

  注意:所有.vue组件文件都必须附上name属性!!!建议用vuex管理cachedViews

<keep-alive :include="cachedViews">
      <router-view></router-view>
</keep-alive>

  2.监测$router的变化;

 watch: {
     // 如果路由有变化,会再次执行该方法
    "$route": "fetchDate"
 }

  但是会在页面离开时再次执行fetchDate,并不是我们需要的,所以可以在to和from上添加执行逻辑,但也是十分的麻烦

//$router是只读状态,所以赋值操作会失效
watch: {
    $route (to, from) {
        if(list.indexOf(from.path) > -1){ //自行添加逻辑,list为你不想有缓存的路径
        this.getData()
        }   
  }
}

  3.在添加keep-alive后会增加两个生命周期mounted>activated、离开时执行deactivated,路由的进入和切换回相应的触发activated和deactivated,这样就可以在每次入路由执行更细致的操作了

//如果是服务端渲染就算了 
activated() {
    //只刷新数据,不改变整体的缓存
    this.fetchDate();
 }

  4.还有更简单粗暴的

//我就笑笑不说话
<div> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view> </div>

  5.还有种情况,在不同路由应用了相同的vue组件

{path:'aaa',component:Mompage,name:'mom'},
{path:'bbb',component:Mompage,name:'momPlus'}

  默认情况下当这两个页面切换时并不会触发vue的created或者mounted钩子,需要手动的watch:$router(又回到上面的步骤),或者在router-view上加上唯一值。

//随便抄一段代码过来
<router-view :key="key"></router-view>
computed: {
    key() {
        return this.$route.name !== undefined? this.$route.name + +new Date(): this.$route + +new Date()
    }
 }

  有错误的,请指出

原文地址:https://www.cnblogs.com/dansingal/p/8302100.html