Home > Net >  looping through variable from rest api and ading it to a v-list
looping through variable from rest api and ading it to a v-list

Time:02-10

I am having some difficulties with the vue.js. The main problem is that I am getting this error :

Property or method `response` is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for `class-based` components, by initializing the property.

My main idea is to loop through the response (which is just an array) and add it to my v-list to have it in shape of something like this :

enter image description here

Instead of having create, read etc. to have my elements of array, and I am wondering how to even start with this problem.

like this is the part with my list in vue.js, I know that I think I need to use v-for method but I cant even start it without solving the error.

            <v-list-group>
              <v-list-item @click="getHosts()">
              {{response}}
              </v-list-item>
              <v-list-item-group>
              </v-list-item-group>
            </v-list-group>
          </v-list>

and this is the function that gets the array.

getHosts(){
      axios.get('http://127.0.0.1:8000/something')
      .then((response)=>{
      console.log(response.data)      
      return response
      })
    }

I've added this function in export default in section methods, I've read about other sections and thought maybe beforeMount but I still got an error.

Thanks for any clues/help/solutions!

CodePudding user response:

Instead of returning the response directly. You can bind the response in the data property.

Working Demo (For demo purpose I am using v-for instead of v-list) :

var vm = new Vue({
  el: '#vue-instance',
  data() {
    return {
      hostList: []
    }
  },
  methods: {
    getHosts() {
        axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
        this.hostList = response.data;
        }).catch((error) => {
        console.warn('API error');
      });
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="vue-instance">
  <button v-on:click="getHosts">Get Hosts!</button>
  <ul>
    <li v-for="host in hostList">
      {{ host.name }}
    </li>
  </ul>
</div>

  • Related