Reputation: 41
I am new to Vue.js and I am trying to code a decision tree but I am having an issue. When people click buttons on a step it loads another step based on a JSON file. The user should be able to skip back to a previous step and have it reset from that set and allow them to work through it from there.
The issue I am having is that the steps that are loaded after choosing a previous step will have the active class still applied. I am pretty sure this has to do with the :key
on the v-for
loop but I don't know how to reset it so that Vue is not saving that setting.
I have setup the code in a Codepen here https://codepen.io/akrug23/pen/jOVYQPd?editors=0011
You can reproduce what I am saying by clicking the following buttons
Manage it myself -> Low -> 0-5 years now click on Medium and you will see that the first button is already set with the class active
Note: Since a lot of the questions are the same I have added numbers to the front so you can see that other questions from the JSON file are loading. I am using Vue.js 3
Thank you in advance.
Upvotes: 1
Views: 175
Reputation: 63059
Change the key in the BranchSteps
component to something unique to the question, like the question
text in item.question
:
<div
v-for="(item, index) in steps"
:key="item.question"
:data-step-id="index"
class="card mb-2 js-step-card"
:class="isLastCard(index)">
The reason for using a key
in a v-for
is so Vue won't reuse any existing DOM nodes when the list is re-rendered, such as when an item is added/destroyed. But it only works if the key is unique to the list item. Sometimes using index
as a key is not unique enough, which is what's happening here.
The unique key above causes Vue to re-render the node with new info instead of reusing the ghost node of the removed item.
Upvotes: 1