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 ответ

Решение

$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 к выражению объекта для привязки. В вашем случае это дочерний элемент с определенным индексом, поэтому обратите внимание, как я изменил input"s v-model привязка к person.children[index],

Я также изменил data возможность быть объектом с одним person имущество. Это сделало привязки в массиве детей работать.

Вот полный рабочий jsFiddle.

Другие вопросы по тегам