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

标签 javascript filter vue.js vuejs2 v-for

我尝试将本地过滤器与 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>

关于javascript - vue v-for 带过滤器给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043897/

相关文章:

javascript - 使用 Javascript 在 iPad 上处理待机

javascript - 如何使用 date-fns 查找一周中最近的一天

javascript - 对多个字段进行数组过滤

vue.js - 视觉 : determine observed object type (distinguish between array and object)

javascript - Vue Mixin 属性为空白/空/非响应式(Reactive)

javascript - CSS Div 滚动高度

javascript - Babel - EC6 到 EC5 的转译

ios - 过滤嵌套数组和字典

reactjs - react : Filter function case insensitive

laravel - Vue组件扩展布局时找不到#app