0

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>
8
  • Make sure you already decalred 'var this.newItems = [];', before pushing new object to array Commented Dec 9, 2019 at 10:51
  • I declared that array. Commented Dec 9, 2019 at 10:54
  • Please add what error log you are getting? Commented Dec 9, 2019 at 10:54
  • "newItems" => array:1 [ 0 => "[object Object]" ]. my object is wrong saved in array Commented Dec 9, 2019 at 10:58
  • So you got this? Also, you v-for is for items while in the code you refer to this.newItems, is it on purpose? Commented Dec 9, 2019 at 10:59

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.