Vue key in depth
Change key to i, todo.text or Math.Random
by Max Sinev
HTML
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="(todo, i) in todos" :key="todo.text">
<label>
<input type="text" ref="inputs">
<del v-if="todo.done">
{{ todo.text }}
</del>
<span v-else>
{{ todo.text }}
</span>
</label>
</li>
</ol>
<button @click="addFirst">Add</button>
<button @click="newTodos">New</button>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
new Vue({
el: "#app",
data: {
todos: [
{ text: 1, done: false },
{ text: 2, done: false },
{ text: 3, done: false },
{ text: 4, done: false }
], inputIndexes: []
},
mounted() {
this.$nextTick(() => {
this.inputIndexes = this.$refs.inputs.map((i, ii) => {
i._index = ii;
i.value = i._index;
return ii;
});
console.log(this.inputIndexes);
})
},
methods: {
newTodos: function() {
this.todos = [
{ text: 6, done: false },
{ text: 7, done: false },
{ text: 8, done: false },
{ text: 9, done: false }
]
this.$nextTick(() => {
this.inputIndexes = this.$refs.inputs.map((i) => {
i.value = i._index;
return i;
})
console.log(this.inputIndexes);
})
},
addFirst: function(){
this.todos.splice(0, 0, { text: Math.random(), done: false });
this.$nextTick(() => {
this.inputIndexes = this.$refs.inputs.map((i) => {
i.value = i._index;
return i._index;
})
console.log(this.inputIndexes);
})
}
}
})