Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep list components alive in Vue

I have a list of components that I render using v-for. Not all the components are shown simultaneously. I page the the array of rendered components by using slice.

These components shouldn't be rerendered, as some of them have user inputted data and some of them do network related tasks.

I tried to use <keep-alive>. However, this renders only the first component.

<keep-alive>
    <component :is="component.type" :key="component.id" v-for="component in components">
</keep-alive>

How do I keep a dynamic list of components alive?

like image 868
Mikko Avatar asked Dec 18 '22 09:12

Mikko


2 Answers

 <div v-for="comp in compList"  :key="'container'+comp.keyId" >
    <keep-alive>
      <component :is="comp.type" :key="comp.keyId"></component>
    </keep-alive>
 </div>

this above works for me . Pushing elements to compList correctly creates new instances of their respective components. Moving an element's index within the array , maintaining key, does not call destroy/create and maintains state within each component

like image 53
yeahdixon Avatar answered Jan 08 '23 05:01

yeahdixon


Tested the answer above in a fiddle and doesn't work. https://jsfiddle.net/z11fe07p/680/

 <div v-for="component in myComponents"  :key="component.id" >
    <keep-alive>
      <component :is="component.type" 
               :name="component.name">
      </component>
    </keep-alive>
 </div>

Also i would avoid using vue reserved words such as components because there is a components key in the vue instance which tells what components the instance is using.

like image 41
Cristi Jora Avatar answered Jan 08 '23 04:01

Cristi Jora