简体   繁体   中英

How do I create keep-alive components that all have the same name in Vue?

I have a list of divs rendered with a v-for. When one of the divs is clicked on, a modal will open, displaying more information about the div.

<PlayerModal :player="selectedPlayer" />

<div v-for="player in players" ...>
    <div @click="openModal(player)">
        {{ player.name }}
    </div>
    ...
</div>

The modal gathers additional information with a get request and displays the information on modal open. I want to save this information, so that when the modal is closed and re-opened, the information would be cached. I thought i could do this with a keep-alive tag. But i don't know how, when the single modal component dynamically renders information from the different divs.

I was thinking I could render one modal-component per div, that way every modal would have its separate keep-alive tag. But the modal components would all have the same name, so i don't know how to activate or deactivate the separate components.

<div v-for="player in players">
    <keep-alive>
        <PlayerModal :player="player" :is=" ??? " />
    </keep-alive>
</div>

Any help is appreciated! Thanks!

simply add a key to the dynamic component

<div v-for="player in players">
   <div @click="openModal(player)">
       {{ player.name }}
   </div>
</div>
<keep-alive max="10">
    <component :player="selectedPlayer" :is="PlayerModal" :key="selectedPlayer.id"/>
</keep-alive>

you can check the cached components by looking at this.$children and the _inactive status of the child component itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM