使用搜索查询过滤数据? WordPress JSON 对象 + VueJS2

Filter data using a search query? Wordpress JSON object + VueJS2

编辑:添加了实时代码编辑器:https://ide.c9.io/dosstx/wordpress

我正在尝试使用 VueJS2 和 Wordpress REST API 过滤 Wordpress JSON 数据对象(在我的真实世界示例中有自定义 post 类型)。

我在连接和让 table 根据输入到搜索框中的搜索词进行过滤时遇到问题。

没有搜索功能,一切正常,但是一旦我尝试使用搜索词进行过滤,什么也没有发生——控制台没有错误。

I have my Vue instance like so:

var vm =  new Vue({
        el: '#app',
        data: {
            searchTerm: '',
            posts: []
        },
        computed: {
            filteredItems: function(){
                return this.posts.filter(function(post) {
                    return this.post.searchTerm; //i believe this line is the culprit
                });
             }
        },
        created: function(){
            $.get('mylocalhost/wp-json/wp/v2/products/' + '?_embed=true')
                .done(function(data) {
                    vm.posts = data;
                 });
         }
 });

My HTML:

<div id="app">
    <form>
        <input type="text" v-model="searchTerm">
    </form>

And further down my HTML....:

<tr v-for="post in filteredItems">
    <td>{{post.title.rendered}}</td>
   ...snip ...
</div>

任何有关如何修复的线索将不胜感激。

您没有正确使用 filter 方法。

来自MDN Docs for the filter method:

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

传递给 filter 的回调应该 return 一个 Boolean 值来确定是否将数组的元素包含在过滤后的数组中。

在你的情况下,我假设你的 post 对象有一些你想要搜索的 属性(比如 content),并且你只想包含包含以下内容的帖子包含搜索词。所以你可以这样做:

computed: {
  filteredItems: function() {
    return this.posts.filter(function(post) {
      return post.content.indexOf(this.searchTerm) != -1; 
    });
  }
},