Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Push object to array, composition api

There is an items. With two selection options "size" (large, small) and quantity (2/4/6) each.

When select each option, need to display in the header what is selected (let’s say small and 4). By clicking the "add to storage" button, it will add it to the storage, on another page it will display a list.

what i tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

vue ts:

const chosenMachines = reactive([]);

const machineInfo = ref({
 size: "Standart",
 glasses: 6
})

const addToList = () => {
 // myStore.addToStoredItems(machineInfo)  ---> storage pinia
 chosenMachines.push(machineInfo.value)
}

template:

<div>Title {{ machineInfo.size  }} | {{ machineInfo.glasses }}</div>       
  <select name="size" v-model='machineInfo.size'  class='selects__select-item'>
    <option>Standart</option>
    <option>Big</option>
  </select>
  <select name="glasses" v-model.number='machineInfo.glasses' class='selects__select-item'>
    <option>6</option>
    <option>8</option>
    <option>12</option>
  </select>
 <button class='btn' @click='sendToStorage'>Add</button>

After adding the first object and beyond the second, the first one is overwritten for some reason. What could be the problem?

>Solution :

Pushing machineInfo.value keeps the reference to the original object in the array. You’ve just made a shallow copy. Any updates to machineInfo.value causes the value in the array to also update. You need to deep copy first before pushing.

chosenMachines.push({...machineInfo.value})

There are many other ways to deep copy, depending on your data one method may be more suitable than another.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading