Skip to content

Commit ff2e37f

Browse files
john-cheesmanchrisvfritz
authored andcommitted
Add id to todo-item component (vuejs#1047)
* Add id to todo-item component Give each todo item an id property to use as the key in the v-for loop. As discussed in #4825. * Fix id generation in simple todos example
1 parent be071a7 commit ff2e37f

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

src/v2/guide/list.md

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,8 @@ Here's a complete example of a simple todo list:
249249
<li
250250
is="todo-item"
251251
v-for="(todo, index) in todos"
252-
v-bind:key="index"
253-
v-bind:title="todo"
252+
v-bind:key="todo.id"
253+
v-bind:title="todo.title"
254254
v-on:remove="todos.splice(index, 1)"
255255
></li>
256256
</ul>
@@ -273,22 +273,35 @@ new Vue({
273273
data: {
274274
newTodoText: '',
275275
todos: [
276-
'Do the dishes',
277-
'Take out the trash',
278-
'Mow the lawn'
279-
]
276+
{
277+
id: 1,
278+
title: 'Do the dishes',
279+
},
280+
{
281+
id: 2,
282+
title: 'Take out the trash',
283+
},
284+
{
285+
id: 3,
286+
title: 'Mow the lawn'
287+
}
288+
],
289+
nextTodoId: 4
280290
},
281291
methods: {
282292
addNewTodo: function () {
283-
this.todos.push(this.newTodoText)
293+
this.todos.push({
294+
id: this.nextTodoId++,
295+
title: this.newTodoText
296+
})
284297
this.newTodoText = ''
285298
}
286299
}
287300
})
288301
```
289302

290303
{% raw %}
291-
<div id="todo-list-example" class="demo">
304+
<div id="todo-list-example">
292305
<input
293306
v-model="newTodoText"
294307
v-on:keyup.enter="addNewTodo"
@@ -298,8 +311,8 @@ new Vue({
298311
<li
299312
is="todo-item"
300313
v-for="(todo, index) in todos"
301-
v-bind:key="index"
302-
v-bind:title="todo"
314+
v-bind:key="todo.id"
315+
v-bind:title="todo.title"
303316
v-on:remove="todos.splice(index, 1)"
304317
></li>
305318
</ul>
@@ -314,19 +327,33 @@ Vue.component('todo-item', {
314327
',
315328
props: ['title']
316329
})
330+
317331
new Vue({
318332
el: '#todo-list-example',
319333
data: {
320334
newTodoText: '',
321335
todos: [
322-
'Do the dishes',
323-
'Take out the trash',
324-
'Mow the lawn'
325-
]
336+
{
337+
id: 1,
338+
title: 'Do the dishes',
339+
},
340+
{
341+
id: 2,
342+
title: 'Take out the trash',
343+
},
344+
{
345+
id: 3,
346+
title: 'Mow the lawn'
347+
}
348+
],
349+
nextTodoId: 4
326350
},
327351
methods: {
328352
addNewTodo: function () {
329-
this.todos.push(this.newTodoText)
353+
this.todos.push({
354+
id: this.nextTodoId++,
355+
title: this.newTodoText
356+
})
330357
this.newTodoText = ''
331358
}
332359
}

0 commit comments

Comments
 (0)