Home » vue » Dynamic v-for rendering from http get results to Vue component

Dynamic v-for rendering from http get results to Vue component

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to achieve a dynamic rendering of elements base from the return items array of the target API endpoint. Below is what I’ve tried

<template id="list-comp-tpl">
    <button @click="searchNow">Search Now</button>
    <ul v-for="item in searchResults">
        <li>{{ item.name }}</li>
    </ul>
</template>

<div id="app">
    <list-comp></list-comp>
</div>

Vue.components('list-comp',{
    template : '#list-comp-tpl',
    data() {
        return {
            searchResults : [];
        }
    },
    method : {
        searchNow(){
          // perform api query
          axios.get('http://apiwebsite.com/search')
          .then(function (response) {
            // handle success
            this.searchResults = response.data.msg;
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
          .then(function () {
            // always executed
          });
        }
    }
});

new Vue({
    el '#app'
});

But the component list-comp is not updating at all like when there’s a return data from the api, it does not display as I expect it to. What can I try next?

Answers:

for me “this” is not visible within function(response)

solutions that work for me

 .then(response => this.searchResults = response.data.msg)

or, If you are keen on function(response) try this:

searchNow(){
      _self = this;
      // perform api query
      axios.get('http://apiwebsite.com/search')
      .then(function (response) {
        // handle success
        _self.searchResults = response.data.msg;
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
    }

###

Try assigning values as shown.

this.searchResults = Object.assign({}, response.data.msg);

The way you are setting the values in array they are not set as reactive property on the DOM. Hence your component is not updated with new data.

You can also use Vue.set for updating array values.

Refer below link.
https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats