首页 > 解决方案 > vue js无法读取未定义的属性

问题描述

我使用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);
  },
}

标签: loopsvue.jspropertiesundefinedv-for

解决方案


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)
    }
  }
}

推荐阅读