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 - 为什么 ForerunnerDB 找不到我的标签?

javascript - 在 Itemselector extJS 中拖放

javascript - Vue.js 禁用动态绑定(bind)?

javascript - 需要 ('net' ).connect 不是一个函数

javascript - 如何隐藏 Angular 网站等功能的源代码?

javascript - Angularjs 过滤器不适用于来自 ng-if 条件的值

java - 在 spring mvc 中使用 servlet 过滤器将现有响应替换为新响应

javascript - Office-JS API : Fetching filtered data from table

vue.js - 将数据从 Component 传递到 Root