简体   繁体   中英

Vue.js v-model data object

So I just started playing around with Vue.js. But I am having some problems with simple tasks like adding new "news item" to the array. JSFiddle included so if someone can tell me what I am doing wrong..

http://jsfiddle.net/pL5taqp6/

HTML

<div id="app">
<input type="text" v-model="news.title">
<input type="text" v-model="news.url">  
<ul>
  <li v-for="n in news">
    {{ n.title }} - {{ n.url }}
  </li>
</ul>
</div>

JS

new Vue({
  el: '#app',
  data: {
    news: [ 
      { title: 'Test Title', url: '/test-title'}
    ]
  }
});

You need a separate method to add items to news array. I added super simple variant of such function.

http://jsfiddle.net/00953sor/

HTML:

<div id="app">

  <form @submit="addItem">
    <input type="text" v-model="itemTitle">
    <input type="text" v-model="itemUrl">
    <button type="submit">Add</button>
  </form>

  <ul>
    <li v-for="n in news">
      {{ n.title }} - {{ n.url }}
    </li>
  </ul>

  <pre>{{ $data | json }}</pre>

</div>

JavaScript:

new Vue({
  el: '#app',
  data: {
    news: [{
      title: 'Test Title',
      url: '/test-title'
    }]
  },
  methods: {
    addItem: function(e) {
      e.preventDefault(); // prevent page refresh
      this.news.push({
        "title": this.itemTitle,
        "url": this.itemUrl
      });
      this.itemTitle = this.itemUrl = '';
    }
  }
});

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