Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve component state with vue-router?

I have a listing/detail use case, where the user can double-click an item in a product list, go to the detail screen to edit and then go back to the listing screen when they're done. I've already done this using the dynamic components technique described here: https://vuejs.org/v2/guide/components.html#Dynamic-Components. But now that I'm planning to use vue-router elsewhere in the application, I'd like to refactor this to use routing instead. With my dynamic components technique, I used keep-alive to ensure that when the user switched back to the list view, the same selection was present as before the edit. But it seems to me that with routing the product list component would be re-rendered, which is not what I want.

Now, it looks like router-view can be wrapped in keep-alive, which would solve one problem but introduce lots of others, as I only want that route kept alive, not all of them (and at present I'm just using a single top level router-view). Vue 2.1 has clearly done something to address this by introducing include and exclude parameters for router-view. But I don't really want to do this either, as it seems very clunky to have to declare up front in my main page all the routes which should or shouldn't use keep-alive. It would be much neater to declare whether I want keep-alive at the point I'm configuring the route (i.e., in the routes array). So what's my best option?

like image 940
John Moore Avatar asked Jan 20 '17 13:01

John Moore


People also ask

What does keep alive do in Vue?

<KeepAlive> is a built-in component that allows us to conditionally cache component instances when dynamically switching between multiple components.

How do I force a component to reload in Vue?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.


1 Answers

You can specify the route you want to keep alive , like:

<keep-alive include="home">   <router-view/> </keep-alive> 

In this case, only home route will be kept alive

like image 126
Alex Garcia Avatar answered Sep 17 '22 14:09

Alex Garcia