使用Vuejs搜索过滤器

时间:2019-02-20 11:52:06

标签: javascript html vue.js vue-component vue-router

我是Vuejs的新手。我正在构建简单的博客应用,并且尝试添加搜索过滤器,但是我遇到了问题。到目前为止,我的代码如下:

<template>
   <div>
      <input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
      <paginate
         name="blogs"
         :list="posts"
         :per="10"
         >
         <section v-for="blog in paginated('blogs')">
            <h2>{{ blog.title }}</h2>
            <router-link :to="'/post/' + blog.id" class="btn btn-primary">read more</router-link>
            <hr>
         </section>
      </paginate>
      <paginate-links
         for="blogs"
         :async="true"
         :show-step-links="true"
         :step-links="{
         next: 'Next',
         prev: 'Previous'
         }"
         :classes="{
         'ul': 'pagination',
         'ul > li': 'page-item',
         'ul > li > a': 'page-link',
         }"
         ></paginate-links>
   </div>
</template>

Javascript:

export default {
  data() {
    return {
      posts: [],
      paginate: ['blogs'],
      searchQuery: ''
    }
  },
  created() {
    this.$http.get("http://jsonplaceholder.typicode.com/posts")
      .then(response => response.json(), error => console.log(error))
      .then(json => this.posts = json, error => console.log(error));
  },
  computed: {
    filteredResources() {
      if (this.searchQuery) {
        return this.posts.filter((post) => {
          return post.title.startsWith(this.searchQuery);
        })
      } else {
        return this.posts;
      }
    }
  }
}

我的搜索无法正常工作,看不到问题出在哪里。有人可以给我有关我的代码的反馈,以便我可以继续进行下去。

1 个答案:

答案 0 :(得分:1)

此作品有效:https://codesandbox.io/s/1y2loo164j

paginate组件中,您应使用

:list="filteredResources"

代替

:list="posts"

如果v-if为空,还应该使用filteredResources块显示所有帖子,例如:

<paginate v-if="filteredResources" ...>
   Search result
</paginate>
<paginate v-else ...>
   All posts
</paginate>