Warm tip: This article is reproduced from serverfault.com, please click

loops-Vue JS无法读取未定义的属性

(loops - vue js cannot read property of undefined)

发布于 2020-11-30 21:24:32

我使用v-for循环列出数组中每个类别的按钮。单击时调用一个函数,但返回错误:

TypeError:无法读取未定义的属性“名称”

每个按钮均正确显示在HTML中,并带有其名称。

v-for循环:

<button :class="{selected: category.exist === true}" v-for="category in categories" :key="category.id" v-on:click="pushFilter(); category.exist = !category.exist">{{ category.name }} {{ category.exist }}</button>

类别数据:

export default {
  data: function () {   
    return {
      categories: [
        {
          name: 'name1',
          exist: false,
        },
        {
          name: 'name2',
          exist: false,
        },
      ],

方法:

methods: {
  pushFilter() {
    console.log(this.category.name);
  },
}
Questioner
Ryley38
Viewed
11
tony19 2020-12-01 05:33:53

pushFilter()引用this.category,但组件没有category属性(至少没有显示问题)。你可能正在尝试访问的category迭代器v-for你可以在模板绑定中传递它:

<button v-for="category in categories" v-on:click="pushFilter(category)">

并更新你的方法以接收category参数:

export default {
  methods: {
    pushFilter(category) {
      console.log(category.name)
    }
  }
}