Keep list components alive in Vue - vue.js

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?

<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

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.

I read source code of Vue's <keep-alive>, and I created new Component which works very well with list.
package name is vue-keep-alive-global. Here is a link, https://www.npmjs.com/package/vue-keep-alive-global
How to use :
<KeepAliveGlobal>
<YourComponent
:key="uniqueKey"
/>
</KeepAliveGlobal>
With Array,
<template v-for="(item, index) of array">
<KeepAliveGlobal :key="`blah-blah-${index}`">
<YourComponent
:item="item"
:key="`your-component-${index}`"
/>
</KeepAliveGlobal>
</template>
KeepAliveGlobal will cache component by key.

There's note at Vue docs about your use case
Note, <keep-alive> is designed for the case where it has one direct
child component that is being toggled. It does not work if you have
v-for inside it. When there are multiple conditional children, as
above, ` requires that only one child is rendered at a
time.
https://v2.vuejs.org/v2/api/#keep-alive
Try v-once directive instead.
https://v2.vuejs.org/v2/api/#v-once

Related

vue3 array value problem between components

i have a strange problem with arrays in vue3
When loading the components, a start array is transferred, in the components the values ​​are taken over with a watcher if the start array changes. that works wonderfully. the whole thing is a little game, the user moves a cone on a certain route.
I switch to another component by changing a page number. the component with the game should actually be completely from the dom, I don't see anything in the tree either.
<transition name="fadepage" mode="out-in" >
<div v-if="getPage()==3">
<VueGameIntro :content="content" :level="level" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" :levelcolor="levelColor" #mqttMessage="changeMqttMessage"></VueGameIntro>
</div>
</transition>
<transition name="fadepage" mode="out-in" >
<div v-if="getPage()==4">
<VueGame :content="content" :level="level" :playerlist="playerList" :startpointlist="startPointList" :levelendstate="levelEndState" :activeplayerlist="activePlayerList" :kegelmoved="kegelMoved" :kontrastswitch="kontrastSwitch" :id="id" #mqttMessage="changeMqttMessage" #changeCurrPoint="changeCurrPoint"></VueGame>
</div>
</transition>
<transition name="fadepage" mode="out-in">
<div v-if="getPage()==5">
<VueGameOutro :content="content" :level="level" :levelendstate="levelEndState" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" #mqttMessage="changeMqttMessage"></VueGameOutro>
</div>
ok, when the first level has been played it changes to another component VueGameOutro, then it goes back to the actual game components with a new level. Suddenly I have the feeling that this array exists twice.
in the console i see different values ​​than in the output on the screen: {{ currPointList }} shows something different than this.currPointList. in the vue dev plugin, however, are the values ​​​​as well as the screen output. but the component definitely has a different starting point than the one in the currPointList.
the value in the console seems to have been the latest from the previous level.
Is that possible? how can I be sure that a component is completely gone?
are there arrays that have different values ​​for string or number?
##########################################################
edited
that's the console output:
currPointList unmounted 25,0,0,0,
currPointList mounted 8,0,0,0,
GAME_MOVE currPointList #move,1,3,1 25,0,0,0,
currPointList before move 25,0,0,0,
currPointList move point updated 3,0,0,0,
as you can see, the 25 is in front of the unmount, then the component is reloaded and gets the 8 once via a property form the parent comp
then a move command arrives via websocket, an mqtt component receives the message and sends it to the game via MITT emitter. there's no other place to change currPointList. the first value jumps back to 25.
the problem occurred because the emitter.on("eventname" ...) was not deleted when removing the components. I also changed the emitter.on to an arrow function.

How to use `v-if` and `v-for` on the same element?

Hi I'm trying to figure out how to use v-if on a iterated element which also uses v-for. I need to check if the current element has any of a series of classes, which are numbers.
so the classes of each article would be:
<article class="post-item post-guide 12 22 19 30 55">...
this is the HTML that renders all:
<article v-if="showIfHasClass" :class="'post-item post-guide ' + guide.categories.toString().replace(/,/g, ' ')"
v-for="(guide, index) in guides" :key="index">
<header>
<h1 class="post-title">
{{ guide.title.rendered}}
</h1>
</header>
</article>
I have tried with methods that check the class of all elements, that works, but i'm trying to use a clean Vue built-in solution with v-if without success, i'm not able to retrieve the class of this in a successful way.
Should showIfHasClass be a computed property? I have tried with that too... but it seems, I'm missing something along the way.
my data I have to check against is an array:
data:{
guides: [...]
selectedCategories: [1, 22, 33, 100, 30];
}
or maybe it is better to directly loop over the guides and check if they have the selectedCategory or not, then remove the element from the guides data array?
What is more effective?
Besides the option to create an additional filtered computed (effectively eliminating the need to use v-for and v-if on the same element), you also have a template level way of dealing with such edge-cases: the <template> tag.
The <template> tag allows you to use arbitrary template logic without actually rendering an extra element. Just remember that, because it doesn't render any element, you have to place the keys from the v-for on the actual elements, like this:
<template v-for="(guide, index) in guides">
<article v-if="isGuideVisible(guide)"
:key="index"
class="post-item post-guide"
:class="[guide.categories.toString().replace(/,/g, ' ')]">
<header>
<h1 v-text="guide.title.rendered" />
</header>
</article>
</template>
isGuideVisible should be a method returning whether the item is rendered, so you don't have to write that logic inside your markup. One advantage of this method is that you can follow your v-if element with a fallback v-else element, should you want to replace the missing items with fallback content. Just remember to also :key="index" the fallback element as well.
Apart from the above use-case, <template> tags come in handy when rendering additional wrapper elements is not an option (would result in invalid HTML markup) (i.e: table > tr > td relations or ol/ul > li relations).
It's mentioned here as "invisible wrapper", but it doesn't have a dedicated section in the docs.
Side note: since you haven't actually shown what's inside guide.categories, I can't advise on it, but there's probably a cleaner way to deal with it than .toString().replace(). If guide.categories is an array of strings, you could simply go: :class="guide.categories".
I think the most Vue way is to create a computed property with filtered items from selected categories, then use that in v-for loop (the idea is to move the business logic away from template).
computed: {
filteredItems(){
return this.guides.filter(e => this.selectedCategories.includes(e.category))
}
}
Also, as a note, it is not recommended to use v-if and v-for on the same element, as it may interfere with the rendering and ordering of loop elements. If you don't want to add another level of nesting, you can loop on a 'template' element.
<template v-for="item in items">
// Note the key is defined on real element, and not on template
<item-element v-if='condition' :key="item.key"></item-element>
</template>

vue multiple tag 'template' in one single file component

I am work in company with big frontend team, and guys use multiple template tag in single file components. Before that I never see something like this, for me it bad practice. But head developers think that I am stuped, when I ask about that.
Can some one please explain me, when I must use it and why? and if it possible please give link to vue documentation.
And yes, we use vuetify.
example:
<template>
<VContainer>
<VRow>
<VCol>
<h2>
{{ title }}
</h2>
<p>
{{ subtitle }}
</p>
</VCol>
</VRow>
<Share />
<template v-if="p.length > 0">
<VRow>
<VCol>
{{ text }}
</VCol>
</VRow>
<VDivider/>
</template>
<template v-for="(t, index) in ts">
<VRow :key="index">
<VCol v-if="t.p.length > 0">
{{ text }}
</VCol>
</VRow>
<VDivider
v-if="index < t.length - 1"
:key="`divider-${index}`"
class="mx-3"
/>
</template>
</VContainer>
</template>
The <template> used here is just a way to handle loops or conditionals without inserting extra nodes into the DOM.
You could put the v-if or v-for directly on the <VRow> instead of on a <template> that wraps it, but sometimes that's undesirable -- if there are already other conditions there that you want to keep separate, or if you want to wrap multiple nodes in the same condition, as in your example where you have both a <VRow> and a <VDivider> contained in a single <template>.
It's not bad practice and has no undesirable performance effect at all. Your head developers should be better able to communicate that to you rather than calling you 'stupid'.
I think it does't matter use multiple template, We should not use div wrapper the condition render Component, the div will insert to DOM.
here is the official documemnt https://v2.vuejs.org/v2/guide/conditional.html#Conditional-Groups-with-v-if-on-lt-template-gt

Vue Js not rendering few components in v-for

I am using v-for for and then showing the components. is rendering fine but inner element is missing. I am unable to understand. You can see two columns are empty but in the console three are 5 components rendered but showing only 3 components. Tell what may be the problem. any help will be appreciated
<div v-for="(counterDate, index) in fulldate_array" >
<template v-if="shift[officer.oid]">
<shiftlayout v-for="(data,shiftKey) in shift[officer.oid][fulldate_array[index]]" :shift_data="data" :shiftKey="shiftKey" :date="singledate_array[index]" :fulldate="fulldate_array[index]" :width="shiftWidth"/>
</template>
</div>

How does a single file component pass context.data?

I loop functional components in the transition-group, and because I didn't pass a key reference to the root element of the tag component to the tag component.
But how does a single file component pass the context.data?
The sample link
https://codesandbox.io/s/rjjmpvwm4n/
https://github.com/vuejs/vue/issues/7777
The <tag> component needs a key to use as its child <span>'s id.
Since <tag> is a functional component, you will have to access to the data via the data. prefix.
So, since you are using <tag v-for="item in list" :key="item"></tag>, inside the <tag>'s template, you can access the key (of context.data) automatically using data.key:
Add :key="data.key" in tag.vue:
<template functional>
<span :key="data.key">tag content</span>
</template>
Demo CodeSandbox: https://codesandbox.io/s/wxmvxnojl?module=%2Fsrc%2Fcomponents%2Ftag.vue