keep-alive 之下新增子路由 不渲染

<keep-alive>
    <router-view :key="realodKey"></router-view>
</keep-alive>
<div @click="reload">刷新</div>
<div @click="add">新增子路由</div>

reload(){
    this.realodKey = Math.random()
}
add(){
    this.$router.push({path:'xxx'})
}

(reload 是为了刷新当前路由用的)

第一次加载的时候一切正常,但是点击新增子路由 页面就空白了(实测了下事这个 key 引起的 去掉就好了,但是这就没了刷新功能)...现在就很为难

再简化一下需求
每个路由都需要被缓存(已实现,和那些 v-if="xxx"的需求不同,那些事部分不需要缓存), 在此之上 新增一个刷新当前路由的功能(这个卡住了)

阅读 4.6k
6 个回答

不多言,上菜。

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <keep-alive :include="cachedView">
      <router-view v-if="!realodKey" :key="$route.name"></router-view>
    </keep-alive>
    <router-view v-if="realodKey" :key="realodKey"></router-view>
    <div @click="reload">刷新</div>
    <div @click="add">新增子路由</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      realodKey: 0,
      cachedView: []
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler() {
        this.realodKey = 0;
        if (!this.cachedView.includes(this.$route.name)) {
          this.cachedView.push(this.$route.name);
        }
      }
    }
  },
  methods: {
    reload() {
      ++this.realodKey;
      this.cachedView = this.cachedView.filter(view => {
        return view !== this.$route.name;
      });
    },
    add() {
      this.$router.push({ path: "/about" });
    }
  }
};
</script>

image.png

<a></a>
<b></b>
<c></c>
<div>刷新</div>

点击刷新 传个参数进去;actived = true

子组件

activated(){
    //判断下 然后调用接口;
    if(actived){
    }
}

这个传参建议是放在vuex;不知道你的 父子层级数;
最重要是请求数据后要恢复actived = false;

<keep-alive>
     <router-view v-if="reload"></router-view>
</keep-alive>
<router-view v-if="!reload"></router-view>
<div @click="reload = false">刷新</div>
data(){
    return{
        reload:true
    }
}
新手上路,请多包涵

建议不要使用key这种方式,可以在组件路由钩子里将路由组件实列引用保存起来,要刷新缓存在跳转前,注销组件

路由后面加上时间戳参数,比如 xxx.com/?t=1602511397

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题