【问题标题】:vue v-for with filter gives error带有过滤器的 vue v-for 给出错误
【发布时间】:2018-04-13 02:58:03
【问题描述】:

我正在尝试使用带有 v-for 的本地过滤器,但出现错误

属性或方法“filterByTitle”未在实例上定义,但 在渲染期间引用。确保此属性是反应性的, 无论是在数据选项中,还是对于基于类的组件,通过 初始化属性。

代码如下

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

【问题讨论】:

  • 你不能在 Vue 2 中使用像这样的过滤器。使用计算属性。
  • 是的,Vue 2 删除了过滤器。伯特在下面的回答解决了这个问题。

标签: javascript filter vue.js vuejs2 v-for


【解决方案1】:

过滤器是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>

【讨论】:

  • 如果我想拥有多个过滤器怎么办。例如filterByTitlefilterByAuthor。你能用计算值做到这一点吗?
  • @locnguyen 当然。您将构建您的计算属性以考虑多个过滤器,如以下答案所示:stackoverflow.com/a/43772871/38065
猜你喜欢
  • 1970-01-01
  • 2017-06-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多