Search code examples
vue.jsvuejs2axiosv-for

Vue Sync Data on v-for


inside my template I have this element:

<template>
  <div>
    <span v-for="item in items">{{item.name}}</span>
  </div>
</template>

in my script I have:

import axios from 'axios';
export default {
    data: () => ({ items: null }),
    mounted: function () {
        var vm = this;
        axios.get('/items')
         .then(function (response) {
          vm.items = response.data;
        });
   }
}

My question is how to do I get <span> elements show up and for the v-for execute once the response returned with a list of items?


Solution

  • You need to wrap spans created by v-for in a single root div:

    <template>
      <div>
        <span v-for="item in items">{{item.name}}</span>
      </div>
    </template>
    

    And also there seems to be a problem with vm.items = response; which should be vm.items = response.data;, See axios response schema for more detail.