【发布时间】:2020-11-27 10:41:57
【问题描述】:
我正在尝试构建一个组件来创建过滤器按钮,然后通过事件总线将过滤器对象中的类型属性发送到我的应用程序的其他地方处理。但是,当我在数据部分添加对象数组(过滤器)时,我收到 this 的错误。单击按钮时未定义过滤器。
我想将过滤器数组保留在此组件中,因为我还尝试将活动类动态更改为已单击的任何按钮。
我错过了与道具有关的东西吗?当 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>
如您所见,注释部分是我最初使用过滤器的地方,但我必须将它们移动到按钮组件才能添加活动类。
【问题讨论】:
-
你可能弄乱了v-for中参数的顺序,通常是(index, value)。此外,您应该避免覆盖道具名称。
-
@andypotato 顺序是正确的
-
我只是对为什么 this.filter 未定义感到困惑。覆盖道具名称是什么意思@andypotato
-
@TylerMorales 你能告诉我们你在哪里使用你的组件吗?我猜您没有将道具传递给您的按钮组件?使用
this.$props,您可以检查它是否可用 -
@Ifaruki 我刚刚编辑了帖子以反映这些变化
标签: javascript list vue.js vue-component v-for