简体   繁体   中英

How to push objects to an array in Vue 3 while i < 5

I am attempting to set up a button function in Vue 3 that handles pushing objects to an array in a for loop, while i < 5:

const addFeatureObjs = () => {
  for (let i = 0; i < 5; i++) {
    // featureObjArray.value.push({ id: null, feature: null })
    featureObjArray.value[i] = { id: null, feature: null }
  }
}

So far, I have a for loop set up to create 5 instances of the object while i < 5. However, I wish to set up this function so that each button click call to addFeatureObjs creates a new object one click at a time until 5 are created, instead of calling addFeatureObjs to create the 5 objects all at once. How can I go about setting up this function, for loop, and array to enable creating each object one at a time, until 5 are created?

Just check the length of the array before pushing:

 const addFeatureObjs = () => { if (featureObjArray.value.length <= 5) { featureObjArray.value.push({ id: null, feature: null }); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM