我正在尝试构建一个组件,该组件创建过滤器按钮,然后通过事件总线发送filters对象中的type属性,以便在我的应用程序中的其他地方进行处理。但是,当我在data部分中添加对象(过滤器)的数组时,当我单击一个按钮时,我得到一个错误this.filter is not defined。
我希望将filters数组保留在此组件中,因为我还尝试将活动类动态更改为所单击的任何按钮。
我是不是遗漏了一些与道具有关的东西?当数据和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>正如您所看到的,注释部分是我最初使用过滤器的地方,但为了添加活动类,我必须将它们移到按钮组件中。
发布于 2020-08-07 14:28:28
是的,你不会将一个道具传递给你的组件,这就是为什么它没有被定义。
<FilterBtn filter="test" />在这里,我传递了一个名为filter的属性,其值为test。
当然你可以通过动态道具。绑定它就行了。
<FilterBtn :filter="yourData" />我需要问一下:您传递的是对象还是字符串?
因为您将prop定义为字符串,但实际上将其用作对象
{{ filter.name }}也许您还应该将类型设置为Object。
props: {
filter: { type: Object }
},https://stackoverflow.com/questions/63295943
复制相似问题