这篇文章的代码改写自Vue官网的示例,主要改动了以下几处:
1.增加了item编号
2.简化v-on / v-bind指令
3.使用es6语法
4.增加了input为空的校验
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://cdn.bootcss.com/vue/2.3.3/vue.js"></script>
</head>
<body>
<div id="todo-list-example">
<input v-model="newTodoText" @keyup.enter="addNewTodo" placeholder="Add a todo">
<ol>
<li
is="todo-item"
v-for="(todo, index) in todos"
:key="index"
:number="index"
:title="todo"
@remove="todos.splice(index, 1)"
></li>
</ol>
</div>
<script type="text/javascript">
Vue.component('todo-item', {
template: `<li>{{ number+1 }}. {{ title }}<button @click="$emit('remove')">X</button></li>`,
props: ['number', 'title']
})
new Vue({
el: '#todo-list-example',
data: {
newTodoText: '',
todos: [
'Do the dishes',
'Take out the trash',
'Mow the lawn'
]
},
methods: {
addNewTodo() {
if (this.newTodoText.trim()==='') return
this.todos.push(this.newTodoText)
this.newTodoText = ''
}
}
})
</script>
</body>
</html>