vue js 无法读取未定义的 属性
vue js cannot read property of undefined
我使用 v-for
循环列出数组中每个类别的按钮。单击时调用了一个函数,但它 returns 出错:
TypeError: Cannot read property 'name' of undefined
每个按钮都正确显示在 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
属性(问题中至少显示了 none)。您可能正在尝试访问 v-for
的 category
迭代器。您可以在模板绑定中传递它:
<button v-for="category in categories" v-on:click="pushFilter(category)">
并更新您的方法以接收 category
参数:
export default {
methods: {
pushFilter(category) {
console.log(category.name)
}
}
}
我使用 v-for
循环列出数组中每个类别的按钮。单击时调用了一个函数,但它 returns 出错:
TypeError: Cannot read property 'name' of undefined
每个按钮都正确显示在 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
属性(问题中至少显示了 none)。您可能正在尝试访问 v-for
的 category
迭代器。您可以在模板绑定中传递它:
<button v-for="category in categories" v-on:click="pushFilter(category)">
并更新您的方法以接收 category
参数:
export default {
methods: {
pushFilter(category) {
console.log(category.name)
}
}
}