Vue Checkbox filter component not working

谁说我不能喝 提交于 2020-07-09 13:12:25

问题


In a single file component I made a checkbox array:

    <label 
      v-for="(category, index) in categories" 
      :key="index"
     >
      <input type="checkbox" :value="category.value"
      @change="emitSearchValue">
      <span class="ml-2 text-gray-700 capitalize">{{ category.value }}</span>
    </label>

With EventBus I transfer the data to the List component:

methods: {
    emitSearchValue() {
      EventBus.$emit('checked-value', 'this.checkedCategories')
    }
  }

In the List component I listen for the EventBus:

created() {
 EventBus.$on('checked-value', (checkedCategories) => {
  this.checkedvalue = checkedCategories;
 })
}

Then my computed property look like this:

computed: {
 filteredData() {

   return this.blogs.filter(blog =>
   // if there are no checkboxes checked. all values will pass otherwise the category must be included
    !this.checkedCategories.length || this.checkedCategories.includes(blog.category)
   )
  }
},

In the console I get:

[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"

Here is a link to a sandbox.

Whats wrong here?


回答1:


Change the computed prop filteredData to:

computed: {
    filteredData() {
      if(!this.checkedvalue.length) return this.experiences

      return this.experiences.filter(experience =>
        this.checkedvalue.includes(experience.category)
      );
    }
}


来源:https://stackoverflow.com/questions/62413901/vue-checkbox-filter-component-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!