Creating an array of objects in Vue based on the length of a loop

I am completely new to Vue and in one of my projects, I need to generate an array of objects based on a specific number. For instance, if the total length value is 3, then I want to create fetchList1, fetchList2, and fetchList3. If the total length value is 2, then it should only create fetchList1 and fetchList2.

The total length value is retrieved from the database, so it can range anywhere from more than 50 to less than 5.

VIEW

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

Method

new Vue({
  el: "#app",
  data: {
    totalLength: '3',
    fetchList1: '',
/** Automatically creates fetchList1, fetchList2, and fetchList3 if the total length is 3 **/
  },
  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;
        }
      }, 
  }
})

Check out the link to my attempt on jsfiddle below

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

Answer №1

If you attempt to dynamically add root data properties in Vue, a warning will be triggered. According to the information found in the documentation:

It is not permitted by Vue to introduce new reactive properties at the root level of an already created instance.

The recommended approach is to create a new array named fetchList:

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

You can then proceed to populate it as follows:

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

Utilizing this.$set (or Vue.set) is necessary when working with arrays and incorporating dynamic indexes.

A demonstration is provided below:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Dynamic Input Binding in Vue.js with an Array of Computed Properties

Currently, I am faced with a situation where I need the v-model binding of an input field to be determined by the computed property's returned value. Take a look at the example provided below: <!DOCTYPE html> <html> <head> <scri ...

The script I added is malfunctioning when I utilize laravel/ui

Recently, I started using a template from node js during a course. While reading various posts, I learned that bootstrap utilizes jquery. It dawned on me that the script placed in the head section was causing issues when inserting scripts in other views. ...

Modify the navbar background color in bootstrap-vuejs

As per the information provided in the documentation, the instructions for setting styles for the navigation bar are as follows: <b-navbar toggleable="lg" type="dark" variant="info"> <!-- Or --> <b-navbar toggleable="lg" type="dark" variant ...

What is the best way to position a popup div in CSS?

Currently, I am in the process of developing a website that displays DVD details when hovering over an image, similar to what is shown in picture 1. However, I've encountered an issue where the content gets cut off for DVDs located on the right side o ...

React JS Button remains unaltered despite API call influence

I have encountered an issue with my page where a single post is displayed and there is a like button. The problem arises when the user clicks the like button - if the post is already liked, the button state should change to an unlike button. However, if th ...

During the testing of a Vue single file component with Jest, the prop being sent is found to be undefined

I am currently working on testing a Vue single file component that takes a prop as an input. However, I am encountering an issue when I try to mock the prop, which is an object. The problem arises in the HTML where the object values are utilized, resulting ...

How can Vue.Draggable's draggable functionality be toggled on and off?

I'm faced with a situation where the elements being wrapped should only be draggable under specific conditions. I managed to handle it in my HTML code like this: <draggable v-if='somePassingConditions'> <my-component></my-comp ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

What is the technique for anchoring elements at the top of the page when scrolling?

There is a common design feature where the sidebar on the left starts at a lower position on the page, but as you scroll it moves up to the top and remains fixed in place instead of disappearing off the screen. This is a popular design trend that I have ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

Only the first result is printed by mysql_fetch_array

Similar Query: Looping through mysql_fetch_array in PHP I am facing an issue with my join query where I try to print out multiple array results using a foreach loop. Despite having 801 results in the array, only the first result gets printed. If anyon ...

Develop a time-sensitive store system using HTML and JavaScript that toggles between open and closed status based on set

I am looking to develop a time-based Open/Closed store using HTML and JavaScript. The concept is that on Fridays, the element with id="friday" should be displayed, otherwise, show the element with id="week". Additionally, if the time i ...

Retrieving Axios error codes within an interceptor

How can error codes like ERR_CONNECTION_REFUSED (indicating the API server is down) and ERR_INTERNET_DISCONNECTED (indicating the local network is down) be accessed when using response interceptors with axios in client-side JavaScript, React, etc.? While ...

Tips for creating curved Extjs area and line charts with a gentle radius to soften the sharp curves

I have been working on a mixed charts component for Extjs, and I noticed that the curves appear too sharp. I am unable to find a configuration option to add radius to the curves. If anyone has experience with this issue, could you please share a method t ...

Optimal Timing for Loading Initial State from Database Using Vuex

In my Vue/Vuex project, I have a simple setup where I retrieve a list of categories from my database using an HTTP GET request. Before implementing Vuex, I used to fetch this data directly in my main component when it was created. Now with Vuex, I have g ...

Include [op.and] in the Sequelize query object

I want to construct my Sequelize query object based on input parameters. It functions well for database keys, as shown in the example below: let query = { where: { id: 5 } } if (inputName) { query['where']['name'] = { nam ...

Tips for implementing a dynamic value in the ng-style based on certain conditions

Is there a way to set a background-color conditionally using ng-style when the color value can be updated from $scope? These are the variables in my scope: $scope.someone = { id: '1', name: 'John', color: '#42a1cd' }; $scope ...

Troubleshooting issue: Event-stream mapSync not functioning properly in async/await scenario

The await commands that I have marked as //******This await does not work */ do not appear to be functioning. It is unclear whether this issue is related to them being in an event stream or if it's a problem with the promise in the imported module. U ...

Is it possible to transfer elements from one array to another when clicked, but without copying the contents to the new array objects?

Welcome, For my latest project, I am excited to create a "Learning Cards" App from scratch. The concept is pretty straightforward: it consists of cards with questions. Upon clicking a button, you can reveal the correct answer. Additionally, there's a ...

Looking for a way to trigger a function on JSTree's refresh event

I have searched through many posts here but cannot find what I am looking for. The version of JSTree that I am using is 3.3.3. My goal is to select a node after a create_node event triggers an AJAX request. Subsequently, JSTree fires the rename_node eve ...