【问题标题】:Vue v-for not updating, even with setVue v-for 不更新,即使有设置
【发布时间】:2018-02-12 10:52:39
【问题描述】:

我有一个呈现数组初始状态的v-for 列表。但是当我将项目添加到数组时,渲染不会更新。 文档和此处的大多数答案都提到您必须使用 this.$set 而不是 array.push(),但在我的情况下这没有帮助。

当调用addTag("thing") 时,“事物”添加到数组中并且它在 Vue 检查器中可见。只是v-for 没有更新。

模板

<span v-for="(tag, index) in project.tags" :key="index">
      {{tag}}    // this renders all the tags that are initially available
</span>

代码(vue typescript类模板)

export default class Student extends Vue {
    project:Project = {} as Project
    newtag : string = ""

    addTag() {
        // adds to array, but v-for not updating
        this.$set(this.project.tags, this.project.tags.length, this.newtag)

        // adds to array, but v-for not updating
        this.project.tags.push(this.newtag)
    }
}

编辑此代码使用typescript class component

【问题讨论】:

  • 为什么不把project放在data里面?
  • 因为它使用了typescript类模板github.com/vuejs/vue-class-component
  • 哇,我不知道这个。谢谢
  • 是的,它非常棒,让代码更具可读性

标签: typescript vue.js v-for vue-class-components


【解决方案1】:

只需要在初始化后给对象添加属性时使用$set,这里不用使用,只需用空标签数组初始化对象即可。

将您的代码更改为如下所示:

export default class Student extends Vue {
   //I'm not a TS expert, so I'm not sure this is the correct way to init
   // a tags array, but you get the point
    project:Project = {tags:[]} as Project
    newtag : string = ""

    addTag() {   
        // adds to array, but v-for not updating
        this.project.tags.push(this.newtag)
    }
}

附带说明,如果您计划动态更改列表(添加/删除标签),则不建议使用索引作为键,否则可能会导致意外行为。最好使用唯一的 id 或标签名称。

【讨论】:

  • 谢谢,就是这样。由于我使用的是打字稿,它开始看起来有点奇怪,我必须告诉编译器我的空数组是正确的类型:project:Project = {tags:[] as string[]} as Project
猜你喜欢
  • 2018-06-20
  • 2016-11-12
  • 2021-05-19
  • 2020-12-15
  • 2018-10-30
  • 2018-05-09
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
相关资源
最近更新 更多