当一次只显示一个时,Vue 似乎正在重用子组件 [英] Vue seems to be reusing child component when only one at a time is showing

查看:28
本文介绍了当一次只显示一个时,Vue 似乎正在重用子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 v-for 循环中渲染子组件,但一次只显示一个.我假设 Vue 将为每个渲染创建一个单独的/新的子组件.

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.

这是预期的行为吗?

  // 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
    }
  },  

推荐答案

是的,重用组件和元素是可以的,它对性能更好.

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

要强制 Vue 创建新实例,请为 key 属性使用唯一值,例如问题 ID:

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"

这篇关于当一次只显示一个时,Vue 似乎正在重用子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆