Home > Software design >  How to prevent the push method from overwriting my items in an array?
How to prevent the push method from overwriting my items in an array?

Time:04-20

I'm studying Typescript and VueJS, and I need to push my array, but it ends up overriding my 'name' property. This is my code:

const itemsSelectedOptions = ref([])    
const nameTemplate = ref('')

function setItem(){
    //@ts-ignore
    itemsSelectedOptions.value.push({name: nameTemplate, fields: [...activities.value.selectedFields]})
}

 <template>
   <div>
     <input v-model="nameTemplate" />
     <button @click="setItem">Save Template</button>
   <div>
 </template>

Everything goes fine on my "fields" property, it doesn't overwrite. But in name always prevails the last value typed in "nameTemplate". Anyway, I'll explain what "selectedFields" would be, they are boxes marked through a select.

CodePudding user response:

As you mentioned, push overwrites the array, use it instead "concat"

Also, I think this link will be helpful.

CodePudding user response:

Vue has issues with push/concats sometimes. I generally overwrite with destructuring.

itemsSelectedOptions.value = [
    ...itemsSelectedOptions.value,
    {name: nameTemplate, fields: [...activities.value.selectedFields]}
]
  • Related