infl8
infl8

Reputation: 21

i want to push object into array of objects in Vue.js

im new to vue and im trying to get the whole concept of vue and how to use it, now im trying to learn lists.

JS:


Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    items: [
    {Name: "qwe"},
    {Name: "qwe"},
    {Name: "zxc"},
    {Name: "qwe"},
    {Name: "asd"}
  ] },
  methods: {
      items.push({Name: "tyu"})
}
})

HTML:

<div id="app">
    <ol>
      <li v-for="item in items">{{item.Name}}</li>
    </ol>
</div> 

Upvotes: 0

Views: 203

Answers (1)

BadPiggie
BadPiggie

Reputation: 6359

The properties of methods property should be a function.

new Vue({
  el: '#app',
  data: {
    items: [
    {Name: "qwe"},
    {Name: "qwe"},
    {Name: "zxc"},
    {Name: "qwe"},
    {Name: "asd"}
  ] },
  methods: {
      // Create a function
      addItem: () => {
         this.items.push({Name: "tyu"});
      }
  }
})

Now you need to call the addItem function.

Using Button Click

<button (click)="addItem()">Add Item</button>

or

<button v-on:click="addItem()">Add Item</button>

On Load

new Vue({
  el: '#app',
  data: {
    items: [
    {Name: "qwe"},
    {Name: "qwe"},
    {Name: "zxc"},
    {Name: "qwe"},
    {Name: "asd"}
  ] },
  methods: {
      addItem: () => {
         this.items.push({Name: "tyu"});
      }
  },
  beforeMount(){
    // Call on page load.
    this.addItem()
  },
})

Vue.Js has an awesome documentation with examples. I strongly recommend you to read it. https://v2.vuejs.org/v2/guide/

Upvotes: 2

Related Questions