Vue 2< keep-alive>不适用于< router-view>和钥匙 [英] Vue 2 <keep-alive> not working with <router-view> and key

查看:45
本文介绍了Vue 2< keep-alive>不适用于< router-view>和钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将vue-router与选项卡等一系列组件一起使用.每个< router-link> 是一个选项卡,下面的空间是< router-view> .其中两个标签是具有不同过滤器的同一组件,假设它们是 products ,并且路由器会添加一个用于过滤的参数:/products/new &/products/sale .

I'm using vue-router with a series of components like tabs. Each <router-link> is a tab and the space below is the <router-view>. Two of the tabs are the same component with different filters, let's say they are products and the router adds a parameter for filtering: /products/new & /products/sale.

<产品> 内是单独的<产品>产品组件,在打开路线时会进行安装.我的问题是,当我在路线之间切换并且更改filter参数时,每次都会重新安装 product 组件.我想将它们缓存起来,这样来回切换就更容易了.为此,我设置了< keep-alive> 并将:key ='$ route.fullPath'添加到我的< router-view> 代码>,但它们似乎没有被缓存.当我在 products 之间切换时,每个 product 仍会触发 mounted()事件.

Inside of products are individual product components which get mounted when the route is opened. My problem is that when I switch between the routes, and the filter parameter is changed, the product components get remounted every time. I'd like to cache them so switching back and forth is easier. To do this I set up <keep-alive> and added :key='$route.fullPath' to my <router-view> but they don't seem to be cached. Each product is still firing a mounted() event when i switch between products.

<keep-alive>
  <router-view :key='$route.fullPath'></router-view>
</keep-alive>

我应该将每个 products 视图放入一个单独的组件中吗?

Should I make each products view into a separate component?

推荐答案

要在路由器视图中使用keep-alive,应在视图路由器上使用唯一键,如下所示:

For use keep-alive with router view you should use unique key on view router like this:

 <keep-alive>
   <router-view :key="$route.fullPath"></router-view> 
 </keep-alive>

不要忘记在保持活动状态时使用max属性来防止内存开销

Dont forgot use max attribute on keep alive to prevent memory overhead

<keep-alive max="5">

或仅包含要缓存的组件:

or just include components want cache:

<keep-alive include="FirstComp,SecondComp"> 

对于组件中的每个组件,如果要缓存,则需要保持活动状态

And for each components inside component you need keep alive them if you want cache

<keep-alive>
  <product></product>
</keep-alive>

这篇关于Vue 2&lt; keep-alive&gt;不适用于&lt; router-view&gt;和钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆