簡體   English   中英

vue2如何添加和觀察數組中的更改元素

[英]vue2 how add and observe changes element in array

我無法通過在輸入中鍵入某些內容來更改child; 如何觀察輸入並使其影響孩子。 並驗證每個孩子是否有名字

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>

$index在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設置為要綁定到的對象的表達式。 在您的情況下,它是特定索引處的child元素,因此請注意我如何將inputv-model綁定更改為person.children[index]

我還將data選項更改為具有單person屬性的對象。 這使得綁定到childs數組的工作。

這是完整的jsFiddle工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM