简体   繁体   中英

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>

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM