javascript - 错误:“v-on 处理程序中的错误:“TypeError:this.filter 未定义”在 vue 中的列表呈现中?
问题描述
我正在尝试构建一个创建过滤器按钮的组件,然后通过事件总线将过滤器对象中的类型属性发送到我的应用程序的其他位置。但是,当我在数据部分添加对象数组(过滤器)时,我收到 this.filter 在单击按钮时未定义的错误。
我想将过滤器数组保留在此组件中,因为我还尝试将活动类动态更改为已单击的任何按钮。
我错过了与道具有关的东西吗?当 data 和 v-for 在另一个组件上时,为什么我无法显示按钮?这些是我为了解决这个问题而一直在问自己的问题。
<template>
<div>
<button
v-for="(filter, index) in filters"
:key="index"
:class="{ active: index === activeItem }"
@click="emitFilter(), selectItem(index)"
:filter="filter"
>
{{ filter.name }}
</button>
</div>
</template>
<script>
import EventBus from '@/components/EventBus'
export default {
props: {
filter: { type: String }
},
data() {
return {
activeItem: 0,
filterResult: '',
filters: [
{ name: 'All', type: 'all' },
{ name: 'Holidays', type: 'holiday' },
{ name: 'Seasons', type: 'season' },
{ name: 'Events', type: 'custom' }
]
}
},
methods: {
emitFilter() {
this.filterResult = this.filter
EventBus.$emit('filter-catagories', this.filterResult)
},
selectItem(index) {
this.activeItem = index
}
}
}
</script>
我的按钮组件用于过滤器组件
<template>
<div>
<span>filters</span>
<FilterBtn />
</div>
</div>
</template>
<script>
import FilterBtn from '@/components/FilterBtn'
export default {
components: {
FilterBtn
}
// data() {
// return {
// filters: [
// { name: 'All', type: 'all' },
// { name: 'Holidays', type: 'holiday' },
// { name: 'Seasons', type: 'season' },
// { name: 'Events', type: 'custom' }
// ]
// }
// }
}
</script>
如您所见,注释部分是我最初使用过滤器的地方,但我必须将它们移动到按钮组件才能添加活动类。
解决方案
我假设您实际上是在尝试从 within访问filter
迭代器。为此,您需要在绑定中传递自身:v-for="(filter, index) in filters"
emitFilter()
filter
@click
<button v-for="(filter, index) in filters"
@click="emitFilter(filter)">
然后,您的处理程序可以直接使用该参数:
export default {
methods: {
emitFilter(filter) {
this.filterResult = filter
//...
}
}
}
推荐阅读
- java - 错误 java.lang.IllegalArgumentException: NamedQuery of name: Employee.findAll not found
- azure - 在 Azure Dev Ops 代理上安装 Az 2.8.0 Powershell 模块
- node.js - REST 命名约定 JOIN
- javascript - 如何在 Kendo react Grid 中同时使用 customCell 和 Reorder?
- java - 在日历视图事件中突出显示数据库中的列表数据
- javascript - 如何在不重新加载页面的情况下更新从 firestore 检索到的标记在我的地图上?
- reactjs - vscode 格式 reactnative 代码和 eslint 冲突
- javascript - React Native:错误:“无法读取未定义的属性'名称',”虽然包含名称的对象不是未定义的
- swift - 是否可以通过协议自定义 UINavigationBar?
- azure-devops - Azure 管道 yaml 权限被拒绝