Vue 2 <保持活动>不使用 <router-view>和钥匙 [英] Vue 2 <keep-alive> not working with <router-view> and key

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

问题描述

我将 vue-router 与一系列组件(如选项卡)一起使用.每个 是一个制表符,下面的空格是 .其中两个选项卡是具有不同过滤器的相同组件,假设它们是 products 并且路由器添加了用于过滤的参数:/products/new &<代码>/产品/销售.

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.

products 内部是单独的 product 组件,它们会在路由打开时安装.我的问题是,当我在路由之间切换并更改过滤器参数时,每次都会重新安装 product 组件.我想缓存它们,以便来回切换更容易.为此,我设置了 并将 :key='$route.fullPath' 添加到我的 code> 但它们似乎没有被缓存.当我在 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>

不要忘记在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;保持活动&gt;不使用 &lt;router-view&gt;和钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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