Push objects to array, composable API
P粉788765679
P粉788765679 2024-04-05 14:41:47
0
1
1631

There is a project. There are two selection options "size" (large, small) and quantity (2/4/6).

When each option is selected, the selection needs to be displayed in the title (assuming a small sum of 4). After clicking the "Add to Storage" button, it will be added to the storage and a list will be displayed on another page.

What I tried:

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>

When adding the first object and the second object thereafter, the first object is overwritten. What is the reason?

P粉788765679
P粉788765679

reply all(1)
P粉464208937

Push machineInfo.value into the array retaining a reference to the original object. You just made a shallow copy. Any updates to machineInfo.value will cause the values ​​in the array to also be updated. You need to make a deep copy before pushing.

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

There are many other ways to do a deep copy, and depending on your data, there may be one method that is more suitable.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template