用vue.js写案例——ToDoList待办事项 (步骤和全码解析)
<template>
<div id="app">
<input v-model="newTodo" @keyup.enter="addTodo" placeholder="Add a task" />
<ul>
<li v-for="(todo, index) in todos" :key="index">
<input type="checkbox" v-model="todo.completed" />
<span :class="{ completed: todo.completed }">{{ todo.item }}</span>
<button @click="removeTodo(index)">X</button>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
newTodo: '',
todos: []
}
},
methods: {
addTodo() {
if (this.newTodo.trim() === '') {
alert('Empty input is not allowed.');
return;
}
this.todos.push({
item: this.newTodo,
completed: false
});
this.newTodo = '';
},
removeTodo(index) {
this.todos.splice(index, 1);
}
}
}
</script>
<style>
.completed {
text-decoration: line-through;
color: grey;
}
</style>
这段代码实现了一个基本的ToDoList功能,用户可以添加任务,标记任务为已完成或删除任务。使用了Vue.js的双向数据绑定和响应式更新特性,使得用户界面与数据模型之间的同步变得更加简单和直观。
评论已关闭