错误:“v-on 处理程序中的错误:“TypeError:this.filter 未定义”

我正在尝试构建一个创建过滤器按钮的组件,然后通过事件总线发送过滤器对象中的类型属性,以便在我的应用程序的其他地方处理。但是,当我在数据部分添加对象(过滤器)数组时,单击按钮时出现 this.filter is not defined 错误。


我想将过滤器数组保留在此组件中,因为我还试图将活动类动态更改为已单击的任何按钮。


我错过了与道具有关的东西吗?当数据和 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>

如您所见,注释部分是我最初拥有过滤器的地方,但我不得不将它们移至按钮组件以添加活动类。


人到中年有点甜
浏览 139回答 4
4回答

拉风的咖菲猫

我假设您实际上是在尝试访问from within的filter迭代器。为此,您需要在绑定中传递itself :v-for="(filter, index) in filters"emitFilter()filter@click<button v-for="(filter, index) in filters"&nbsp; &nbsp; &nbsp; &nbsp; @click="emitFilter(filter)">然后,您的处理程序可以直接使用参数:export default {&nbsp; methods: {&nbsp; &nbsp; emitFilter(filter) {&nbsp; &nbsp; &nbsp; this.filterResult = filter&nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; }&nbsp; }}

白板的微信

您正在将一个名为filtertyped的道具传递string给您的组件。当您输出时,{{ filter.name }}您实际上是在引用此属性,而不是filter您在 v-for 循环中创建的变量。除非您将名为“filter”的属性传递给您的组件,否则该属性将是未定义的。因此输出filter.name将导致此错误消息。

陪伴而非守候

您正在将一个名为filtertyped的道具传递string给您的组件。当您输出时,{{ filter.name }}您实际上是在引用此属性,而不是filter您在 v-for 循环中创建的变量。除非您将名为“filter”的属性传递给您的组件,否则该属性将是未定义的。因此输出filter.name将导致此错误消息。

回首忆惘然

是的,你没有将 prop 传递给你的组件,这就是为什么它是未定义的。<FilterBtn&nbsp;filter="test"&nbsp;/>在这里,我传递了一个名为 propfilter的值test。当然你可以传递动态道具。绑定就行了<FilterBtn&nbsp;:filter="yourData"&nbsp;/>我需要问:你传递的是对象还是字符串?因为您将 prop 定义为字符串,但实际上将其用作对象&nbsp;&nbsp;{{&nbsp;filter.name&nbsp;}}也许您还应该将类型设置为 Object。&nbsp;&nbsp;props:&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;filter:&nbsp;{&nbsp;type:&nbsp;Object&nbsp;} &nbsp;&nbsp;},
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript