Skip to content
Advertisement

how to filter post by title using Vue js 2.x directives instead of vue js 1.x

I am learning to use vue js with wprest api by following watch-learn tutorials on the same topic. the problem is that the vue js version used in the tutorial seems to be v 1.x and i started using vue js 2.x. I was able to figure out the initial stages on how to display all the post using vue js 2.x.. I have an input field using which I search for a specific title it should filter and show the post. The issue is unable to workout exactly how it needs to be computed using vuejs 2.x.. I have included a codepen link containing the json data as well as my working code.

the following is the input field to be used to filter the posts by title

<div class="row">
    <h4>Filter by name:</h4>
    <input type="text" name="" v-model="nameFilter">
</div>
<div class="row">
    <div class="col-md-4" v-for="post in posts">
        <div class="card post">
            <img class="card-img-top" v-bind:src="post.fi_300x180" >
            <div class="card-body">
                <h2 class="card-text">{{ post.title.rendered }}</h2>
                <small class="tags" v-for="category in post.cats">{{ category.name }}</small>
            </div>
        </div> <!-- .post -->
    </div> <!-- .col-md-4 -->
</div> <!-- .row -->

https://codepen.io/dhivyasolomon/pen/LdZKJY

I would appreciate any help in figuring out the next step. thanks.

Advertisement

Answer

You don’t need directives, achieve this using the power of Computed properties

So you will have to itarate over the computed property which filter the posts by the input value and return a new array of posts.

Little example:

new Vue({
  el: '#example',
  computed: {
    filteredPosts () {
      return this.posts.filter(p => p.title.toLowerCase().includes(this.filterText.toLowerCase()))
    }
  },
  data () {
    return {
      filterText: '',
      posts: [
        {
          title: 'My first post title',
          body: 'foo'
        },
        {
          title: 'Another post title',
          body: 'foo'
        },
        {
          title: 'This will work fine',
          body: 'foo'
        },
        {
          title: 'Omg it's working!',
          body: 'foo'
        }
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>


<div id="example">
  
  <input type="text" v-model="filterText" />
  
  <ul>
    <li v-for="post in filteredPosts">{{ post.title }}</li>
  </ul>

</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement