Skip to content
Advertisement

vue v-for with filter gives error

I’m trying to use a local filter with v-for but I’m getting an error

Property or method “filterByTitle” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Code below

<template>
  <div class="row">
    <div class="col pt-5">

      <ul class="blog-list-single" v-for="(post, index) in posts | filterByTitle" :key="index">
        <li class="title">{{ post.title }}</li>
        <li class="author">{{ post.author }}</li>
      </ul>

    </div>
  </div>
</template>

<style lang="scss">
</style>

<script>
  export default {
    data() {
      return {
        posts: [
          { title: 'a', author: 'nd' },
          { title: 'b', author: 'nd' },
          { title: 'c', author: 'nd' },
        ],
        selectedValue: 'a',
      }
    },
    filters: {
      filterByTitle(value) {
        return value.filter(el => el.title == this.selectedValue)
      }
    },
  }
</script>

Advertisement

Answer

Filters are limited in Vue 2 primarily to formatting string interpolations. You can also now use them in v-bind expressions.

In Vue 2, you would filter a list like this using a computed property.

console.clear()
new Vue({
  el: ".row",
  data() {
    return {
      posts: [{
          title: 'a',
          author: 'nd'
        },
        {
          title: 'b',
          author: 'nd'
        },
        {
          title: 'c',
          author: 'nd'
        },
      ],
      selectedValue: 'a',
    }
  },
  computed: {
    filterByTitle() {
      // return the whole list if there is no filter value
      if (!this.selectedValue) return this.posts
      // otherwise return the list filtered by title
      return this.posts.filter(el => el.title == this.selectedValue)
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="row">
  <div class="col pt-5">

    <ul class="blog-list-single" v-for="(post, index) in filterByTitle" :key="index">
      <li class="title">{{ post.title }}</li>
      <li class="author">{{ post.author }}</li>
    </ul>

  </div>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement