为什么在使用 v-for 时 Vue 中的值没有正确更新?

Why value doesn't updated correctly in Vue when using v-for?

我已经创建了基本的 jsfiddle here

var child = Vue.component('my-child', {
    template: 
    '<div> '+
      '<div>message: <input v-model="mytodoText"></div>  <div>todo text: {{todoText}}</div>'+
      '<button @click="remove">remove</button>' +
    '</div>',
    props:['todoText'],
    data: function(){
        return {
        mytodoText: this.todoText
      }
    },
    methods: {
        remove: function(){
        this.$emit('completed', this.mytodoText);
      }
    }
});

var root = Vue.component('my-component', {
    template: '<div><my-child v-for="(todo, index) in mytodos" v-bind:index="index" v-bind:todoText="todo" v-on:completed="completed"></my-child></div>',
    props:['todos'],
    data: function(){
        return {
        mytodos: this.todos
      }
    },
    methods: {
        completed: function(todo){
        console.log(todo);
        var index = this.mytodos.indexOf(todo, 0);
        if (index > -1) {
            this.mytodos.splice(index, 1);
        }
      }
    }
});

new Vue({
  el: "#app",
  render: function (h) { return h(root, {
      props: {todos: ['text 1', 'text 2', 'text 3']}
    }); 
  }
});

代码很简单:根组件接收待办事项(字符串)数组,使用子组件迭代它们并通过 props 传递一些值 单击顶部的 "remove" 按钮,您将看到结果 - 我希望有

message: text 2 todo text: text 2

而是拥有:

message: text 1 todo text: text 2

根据我的理解,vue 应该删除第一个元素并保留其余元素。但实际上我有某种 "mix"。

您能解释一下为什么会发生这种情况以及它是如何工作的吗?

这是因为 Vue 尝试 "reuse" DOM 元素以最小化 DOM 突变。参见:https://vuejs.org/v2/guide/list.html#key

您需要为每个子组件分配一个唯一键:

v-bind:key="Math.random()"

在 real-world 中,键可以是例如从数据库中提取的 ID。