Vue 2 <保持活力>不适用于 <router-view>和钥匙
我正在使用带有一系列组件(如选项卡)的 vue-router.每个
是一个选项卡,下面的空格是
.其中两个选项卡是具有不同过滤器的相同组件,假设它们是 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
.
products
内部是单独的 product
组件,这些组件会在路由打开时安装.我的问题是,当我在路由之间切换并更改过滤器参数时,product
组件每次都会重新安装.我想缓存它们,这样来回切换更容易.为此,我设置了 <keep-alive>
并将 :key='$route.fullPath'
添加到我的 <router-view>
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>
不要忘记在保持活动状态时使用 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>
相关文章