Technologies:
Tolerim
a month ago
What measures can be taken to stop vue3 from regenerating elements in DOM while adding an element to a reactive array?
In vue3, I have an array that represents tabs, and I add an object to it when a new tab is opened by button click. The current code I have generates all of the TabContent objects and executes their onMounted methods every time a new object is added to the array. This results in low efficiency. Is there a way for me to only add the new component to the DOM and disregard the others?
To provide more context, tabs is defined as "const tabs = ref([] as Tab[]);"
Here is the code I am currently using:
Thank you for your help!Answers(1)
Tolerim
a month ago
Verified Answer
Yes, there is a way to add only the new component to the DOM and ignore the rest. In Vue 3, you can use the keep-alive component to cache and preserve the state of a component instead of recreating it every time it's toggled. Here's how you can modify your code:
<template v-for="(tab, i) in tabs" :key="tab.id">
<keep-alive>
<TabContent
v-if="selected_request(tab.request.id)"
v-show="tab.id === selected_tab?.id"
v-model:tab="tabs[i]"
v-model:api-call-loading="api_call_loading"
v-model:specs-loading="specs_loading"
:request="selected_request(tab.request.id)"
:requests="requests"
:accounts="accounts"
:servers="servers"
:result="result"
:instance="null"
:acquire-token="GetNewToken"
/>
</keep-alive>
</template>
Wrapping the TabContent component with the keep-alive component will cache it when it's toggled and preserve its state. When you add a new object to the tabs array, Vue will only add the new TabContent component to the DOM and preserve the state of the previously cached components, which means that it won't execute their onMounted hooks again because they are still cached in memory.