Search code examples
vue.jsvuejs3vue-composition-api

setup VueJS get data


I have trouble getting data. I get data with axios and print them with console.log, here what I have in the console :

I see my data and the lenght but I do not succeed to use them in my code. I would like for exemple to do a for like that :

for(var i; i<temp.length; i++){
        console.log(temp.name)
      }

This do not work since temp.lenght give 0. Or I just want to print my first argument name: MONITOR ... but I do not suceed either.

Do you know how we do that ?

Here the rest of my code :

setup() {
    const temp=[];
    onMounted(() => {
      axios.get('http://localhost:8080/data/mock.json')
          .then((data) => (temp.value = data.data.data))
      console.log(temp)
      for(var i; i<temp.valueOf().length; i++){
        console.log(temp.name)
      }
    });
return{temp}
}

Solution

  • You should put the for loop inside the then callback and use ref to init temp :

    import {ref} from 'vue'
    ...
    setup() {
        const temp=ref([]);
        onMounted(() => {
          axios.get('http://localhost:8080/data/mock.json')
              .then((data) => {
                 temp.value = data.data.data
                   for(var i; i<temp.value.length; i++){
                       console.log(temp.name)
                    }
    
              })
          console.log(temp)
        
        });
    
    
       return{temp}
    }