Vue generate array of objects according to loop length

Viewed 502

I am really new to Vue and for one project I am trying to create an array of objects according to a number. For example, if the total length value is 3 then is there a way to create fetchList1, fetchList2 and fetchList3? If the total length value is 2 then it should create the data return object as fetchList1 and fetchList2.

I am getting the total length value from database so it can be more than 50 and less than 5 sometimes.

VIEW

<div id="app">
  <button @click="grabTeams()">
   CLICK ME
  </button>
</div>

Method

new Vue({
  el: "#app",
  data: {
    totalLength: '3',
    fetchList1: '', 
/** if the total length is 3 then it should automatically create fetchList1, fetchList2 and fetchList3 **/
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    },
    
    grabTeams(){

        console.log('Total value length ' +this.totalLength);

        for(let b=0; b < this.totalLength; b++){
          console.log('value of '+b);
          var replyDataObj1 = parseInt(b);

            replyDataObj1={
              "id" : b
            }

            this['fetchList'+b] = replyDataObj1;
        }
      }, 
  }
})

Below is the link that I tried on jsfiddle

https://jsfiddle.net/ujjumaki/8xq9wn1m/14/

1 Answers

Vue will throw a warning if you try to dynamically add root data properties. From the docs:

Vue does not allow dynamically adding new root-level reactive properties to an already created instance.

Instead, make a fetchList array:

data() {
   return {
      fetchList: []
   }
}

Add to it:

for(let b = 0; b < this.totalLength; b++){
   this.$set(this.fetchList, b, {
      id: b
   })
};

You have to use this.$set (or Vue.set) because you are adding dynamic indexes to the array.

Here's a demo:

new Vue({
  el: "#app",
  data: {
    totalLength: '10',
    fetchList: [],
  },
  methods: {
    toggle: function(todo){
      todo.done = !todo.done
    },
    grabTeams(){
      for(let b = 0; b < this.totalLength; b++){
         this.$set(this.fetchList, b, {
            id: b
         })
      }
    }
  }
})
<div id="app">
  <button @click="grabTeams()">
   CLICK ME
  </button>
  {{ fetchList }}
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Related