loops - 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);
},
}
解决方案
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)
}
}
}
推荐阅读
- javascript - ReactJS 如何正确调用多个函数
- json - 从 groovy 中的 JSONArray 中删除特定的 JSONObject
- javascript - 如何使用 setTimeout 中的参数解决承诺
- python - 如何在 django 模型中向 integerField 添加数字?
- azure - Azure ML Compute Instance: How can I safely upgrade the default Azure Ubuntu 16.04 LTS to the latest LTS?
- php - 除 WooCommerce 中的几个特定产品外,最小购物车数量
- php - 如何通过 php 脚本在 Ajax 中发送响应
- html - HTML边距对css没有反应
- scala - Dynamic dataframe with n columns and m rows
- javascript - 如何从隐藏元素中删除无限动画