meow
meow

Reputation: 28174

Vue seems to be reusing child component when only one at a time is showing

I am rendering child components in a v-for loop, but only showing one at a time. I assumed that Vue will create a seperate/new child component for each render.

But it appears to be using the same instance, since my data values in the child component persist even after being changed out.

Right now, i am creating a watcher to reset the data values manually when the question changes.. but that feels hacky.

Is this an expected behavior?

  // Parent Component
    <AnswerQuestion
      v-for = "question in questions"
      v-bind:question = "question"
      v-if = "question.id == currentVisibleIndex"
      v-on:questionAnswered = "questionAnswered"
      >
    </AnswerQuestion>



  // Child Component
  props: ["question"],
  data() {
    return {
      options: options,
      commentText: null
    }
  }

  // what i am doing now, feels hacky
  watch: {
    question: function (newQuestion) {
      this.selectedOption = null
      this.commentText = null
    }
  },  

Upvotes: 5

Views: 2883

Answers (2)

Linus Borg
Linus Borg

Reputation: 23988

Yes, reusing components and elements is expected, it's better for performance.

To force Vue to create fresh instances, use a unique value for the key property, for example the question id:

v-bind:key="question.id"

Upvotes: 10

Cassio Cabral
Cassio Cabral

Reputation: 2692

Try to use v-show instead of v-if: v-show= "question.id === currentVisibleIndex"(triple equals is better).

v-if will render only when that condition is met, v-show will render all the Answer components but will only show the one with currentVisibleIndex.

You can move the this.selectedOption = null(selectedOption, actually) inside the data, that meaning that will be initialized with null. Another option is to use as prop and set the default return as null as well.

Upvotes: 1

Related Questions