vue2如何添加和观察数组中的更改元素

时间:2016-10-09 18:01:56

标签: javascript vue.js two-way

我无法通过在输入中键入内容来改变孩子; 如何观察输入并使其影响孩子。 并验证每个孩子是否有姓名

js:

     $(function () {
       var person = {
           name: '',
           children: ['Please enter a name']
       }

       var vm = new Vue({
           el: "#example",
           data: person,
           methods: {
               addChild: function (index) {
                   this.children.splice(index+1, 0, ""); //
               },
               removeChild: function (index) {
                   this.children.splice(index , 1)
               },
               getData: function () {
                   console.log(this.children);
               }
           }    
       })

   })

html部分:

<ul >
    <li v-for="(child,index) in children">
        the child at <span>{{ index }}</span> is <span >{{ child }}</span>
        <input v-model = "child">
        <button @click="addChild(index)">newChild</button>
        <button v-on:click="removeChild(index)">X</button>

    </li>
</ul>
    <button v-on:click="getData">watch data</button>
    <div>{{ $data | json }} </div>

</div>

1 个答案:

答案 0 :(得分:1)

$indexbeen deprecated in Vue 2.x。相反,您可以将变量作为v-for指令的一部分分配给索引:

<li v-for="(child,index) in person.children">
    the child at <span>{{ index }}</span> is <span >{{ child }}</span>
    <input v-model = "person.children[index]">
    <button @click="addChild(index)">newChild</button>
    <button v-on:click="removeChild(index)">X</button>
</li>

<强>已更新

好的,我知道你现在在做什么。您可以将v-model设置为要绑定的对象的表达式。在您的情况下,它是特定索引处的子元素,因此请注意我将input v-model绑定更改为person.children[index]的方式。

我还将data选项更改为具有单个person属性的对象。这使绑定到子数组工作。

这里是complete working jsFiddle

相关问题