Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

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"的需求不同,那些事部分不需要缓存), 在此之上 新增一个刷新当前路由的功能(这个卡住了)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

不多言,上菜。

<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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...