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
663 views
in Technique[技术] by (71.8m points)

javascript - Vue 2 <keep-alive> not working with <router-view> and key

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.

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>

Should I make each products view into a separate component?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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>

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>

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

...