[Vuejs]-Filter Posts form API in VueJS

1👍

I suspect — from the test data in your prior edit — you have post url mixed up with some image url buried deeper in the post data. As proof that the problem lies elsewhere, see the following snippet. You can find posts by inputting (case-sensitive) text that appears in the titles…

function pretendAxios() {
  const data = [{
      url: 'some url A',
      description: 'description A',
      title: 'Strawberry Fields Forever'
    },
    {
      url: 'some url B',
      description: 'description B',
      title: 'In My Life'
    },
    {
      url: 'some url C',
      description: 'description C',
      title: 'I Want To Hold Your Hand'
    },
  ];
  return Promise.resolve({
    data
  })
}

var app = new Vue({
  el: '#app',
  data() {
    return {
      keyword: '',
      posts: [],
    }
  },
  computed: {
    filterPosts() {
      const {
        posts,
        keyword
      } = this
      return posts.filter(({
        title
      }) => title.includes(keyword))
    }
  },

  methods: {
    loadPosts() {
      let self = this
      pretendAxios()
        //.get('http://localhost/test/wp-json/posts/v1/object')
        .then(function(response) {
          self.posts = response.data
        })
        .catch((error) => {
          console.log(error)
        })
    },
  },

  mounted() {
    this.loadPosts()
  },
})
<head>
  <meta charset="utf-8" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>

<body>
  <div id="app">

    <div class="pb-8 pt-4">
      <input type="text" v-model="keyword" placeholder="Type a case sensitive title word" class="p-4 border border-gray-500 font-light xmy-4 w-full" />
    </div>
    <div v-for="(post, index) of filterPosts" :key="index">
      <p>{{ post.title }}, {{ post.url }}, {{ post.description }}</p>
    </div>
  </div>
</body>

Note that the use of "self" in loadPosts() is unnecessary.

Leave a comment