我使用v-for
循环列出数组中每个类别的按钮。点击时调用函数,但返回错误:
TypeError:无法读取未定义的属性"name">
每个按钮都以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);
},
}
pushFilter()
引用this.category
,但组件没有category
道具(至少没有显示任何问题(。您可能正在尝试访问v-for
的category
迭代器。你可以在模板绑定中传递它:
<button v-for="category in categories" v-on:click="pushFilter(category)">
并更新您的方法以接收category
参数:
export default {
methods: {
pushFilter(category) {
console.log(category.name)
}
}
}