Sayed Sajad Hosseini
Sayed Sajad Hosseini

Reputation: 233

How to push object to existing array in Vue.js

In the below code I have a value and that is an object how to can I push to the exist array.

methods: {
  onChange(event) {
    this.newItems.push(event.target.value);
    console.log(event.target.value);
  }
}

and my blade is:

<select @change='onChange($event)' class="form-control">
  <option value="" selected disabled>Choose</option>
  <option v-for='item,key in items' :value="item">@{{ item.name }}</option>
</select>

Upvotes: 0

Views: 3437

Answers (1)

MartinSRimsbo
MartinSRimsbo

Reputation: 226

I would suggest using v-model on the select to detect which is currently selected.

<div id="app">
  <select @change="onChange" class="form-control" v-model="selected">
   <option value="" selected disabled>Choose</option>
   <option v-for='item,key in items' :value="item">@{{ item.name }}
   </option>
</select>
<p v-for="newItem in newItems">
  {{newItem}}
</p>
</div>

and then push this.selected in your onChange method instead:

this.newItems.push(this.selected)

Hope this helps.

Working fiddle of your code with some small modifications:

https://jsfiddle.net/MapletoneMartin/e4oth98p/7/

Upvotes: 1

Related Questions