带有过滤器的 vue v-for 给出错误

vue v-for with filter gives error

我正在尝试将本地过滤器与 v-for 一起使用,但出现错误

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.

下面的代码

<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>

过滤器 limited in Vue 2 主要用于格式化字符串插值。您现在也可以在 v-bind 表达式中使用它们。

在 Vue 2 中,您将使用计算的 属性.

过滤这样的列表

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>