search

Home  >  Q&A  >  body text

Push objects to array, composable API

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粉788765679P粉788765679258 days ago1670

reply all(1)I'll reply

  • P粉464208937

    P粉4642089372024-04-06 12:05:10

    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.

    reply
    0
  • Cancelreply