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