EDIT: Live Code Editor added: https://ide.c9.io/dosstx/wordpress
I am trying to filter a Wordpress JSON data object using VueJS2 and the Wordpress REST API (I have a custom post type in my real world example).
I'm having trouble with the wiring and getting the table to filter based on the search terms that are typed into the search box.
Without the search function, everything works fine, but once I try to filter using a searchterm, nothing happens -- no error in console.
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>
Any clues on how to fix would be greatly appreciated.
You aren't using the filter
method correctly.
From the 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 totrue
.
The callback passed to filter
should return a Boolean
value to determine whether or not to include the element of the array in the filtered array.
In your case, I'm assuming your post
objects have some property (say content
) you want to search and that you want to only include posts with content that contain the search term. So you can do something like this:
computed: {
filteredItems: function() {
return this.posts.filter(function(post) {
return post.content.indexOf(this.searchTerm) != -1;
});
}
},