首页 > 解决方案 > 错误:“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>

如您所见,注释部分是我最初使用过滤器的地方,但我必须将它们移动到按钮组件才能添加活动类。

标签: javascriptlistvue.jsvue-componentv-for

解决方案


我假设您实际上是在尝试从 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
      //...
    }
  }
}

推荐阅读