Vue 3 保持活动缓存路由

2022-01-25 00:00:00 html vue.js vue-router vue-component vuejs3

我正在使用 Vue 3 <keep-alive>.当我不使用 :key 时,它会缓存(按预期不正确地跨不同的 URL).

I'm using Vue 3 <keep-alive>. When I don't use :key it caches (improperly across different URLs as expected).

通过添加

<router-view :key="$route.fullPath" v-slot="{ Component }">
  <keep-alive>
    <component :is="Component" />
  </keep-alive>
</router-view>

我认为它只会在缓存键不存在的情况下进行 API 调用,这样当我转到不同的路线并返回时,它不会进行第二次 API 调用.

I would think that it only makes an API call if the cache key doesnt exist, so that when I go to a different route and come back, it won't make a second api call.

但是当我现在添加 :key="$route.fullPath" 时,即使我重新访问同一个 URL,它每次都会调用 API?

But when I add :key="$route.fullPath" now it makes an API call every single time even if I revisit the same URL?

推荐答案

在 Vue 3 中,将 key 放在 而不是 <路由器视图>:

In Vue 3, put the key on the <component> rather than the <router-view>:

<router-view v-slot="{ Component }">
  <keep-alive>
    <component :is="Component" :key="$route.fullPath"></component>
  </keep-alive>
</router-view>

相关文章