javascript - Vue.js v-model data object - Stack Overflow

So I just started playing around with Vue.js. But I am having some problems with simple tasks like addi

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..

/

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'}
    ]
  }
});

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/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'}
    ]
  }
});
Share Improve this question edited Mar 27, 2019 at 19:22 Iurii Tkachenko 3,19930 silver badges36 bronze badges asked Dec 6, 2015 at 20:21 VerbaVerba 3882 gold badges6 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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

http://jsfiddle/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 = '';
    }
  }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742353106a4427906.html

相关推荐

  • javascript - Vue.js v-model data object - Stack Overflow

    So I just started playing around with Vue.js. But I am having some problems with simple tasks like addi

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信