2016-10-09 6 views
0

入力で何かをタイプで変更することはできません。 入力を観察して子供に影響を与える方法。 と名前がそれぞれの子のためにvue2どのように追加して、変更の要素を配列で観察しますか?

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

$indexbeen deprecated in Vue 2.xを持っています。代わりに、あなたはv-forディレクティブの一部としてインデックスに変数を割り当てることができます。[OK]を

を更新し

<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を設定できます。あなたのケースでは、特定のインデックスの子要素なので、inputv-modelバインディングをperson.children[index]に変更したことに気づくでしょう。

dataオプションを、personという単一のプロパティを持つオブジェクトに変更しました。これにより、子配列へのバインディングが機能しました。

ここにはcomplete working jsFiddleがあります。

+0

ありがとうございます。オブジェクトのarrrayの代わりに['child1'、 'child2']のような項目の配列を使用できますか? –

+0

なぜ表示されないのですか。 – PatrickSteele

+0

インデックスは機能しますが、入力がデータに影響を与えることはありません。理由はありません。 –

関連する問題