使用vue实现todo清单
ps:如果着急使用可直接看完整实现代码喔
考虑todo清单视图上所需要的东西
todo清单需要一个输入框加入待办事项,并有点击按钮实现添加功能
还需要一个无序列表来展示今日待办事件和实现删除事件功能
那么就先实现视图部分,具体代码如下
<div id="todo-list-example">
<form >
<label >添加 todo</label>
<input
placeholder="请输入新的待办事件"
/>
<button>添加</button>
</form>
<ul>
<todo-item
v-for="(todo, index) in todos"
:key="todo.id"
:title="todo.title"
></todo-item>
</ul>
</div>
考虑添加和删除功能的实现
添加
首先定义一个数组todos存入所有待办事项的id和title,想要实现添加,可以使用push方法向数组推进,并定义一个变量newTodoText绑定在搜索框,用于每次接收新的待办事项
具体定义添加方法和绑定代码如下
//view视图
<form v-on:submit.prevent="addNewTodo">
<label for="new-todo">添加 todo</label>
<input
v-model="newTodoText"
id="new-todo"
placeholder="请输入新的待办事件"
/>
<button>添加</button>
</form>
//方法部分
methods: {
addNewTodo() {
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText
})
this.newTodoText = ''
}
}
})
删除
使用splice,这里也用到了局部注册组件
<button @click="$emit('remove')">删除</button>
: 这是一个按钮,当点击时,它会触发一个名为 remove
的自定义事件。这是通过 Vue 的 @click
指令和 $emit
方法实现的。
具体实现代码如下
//视图部分
<ul>
<todo-item
v-for="(todo, index) in todos"
:key="todo.id"
:title="todo.title"
@remove="todos.splice(index, 1)"
></todo-item>
</ul>
//注册和绑定部分
app.component('todo-item', {
template: `
<li>
{{ title }}
<button @click="$emit('remove')">删除</button>
</li>
`,
props: ['title'],
emits: ['remove']
})
完整实现代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="todo-list-example">
<form v-on:submit.prevent="addNewTodo">
<label for="new-todo">添加 todo</label>
<input
v-model="newTodoText"
id="new-todo"
placeholder="请输入新的待办事件"
/>
<button>添加</button>
</form>
<ul>
<todo-item
v-for="(todo, index) in todos"
:key="todo.id"
:title="todo.title"
@remove="todos.splice(index, 1)"
></todo-item>
</ul>
</div>
<script>
const app = Vue.createApp({
data() {
return {
newTodoText: '',
todos: [
{
id: 1,
title: '看电影'
},
{
id: 2,
title: '吃饭'
},
{
id: 3,
title: '上 RUNOOB 学习'
}
],
nextTodoId: 4
}
},
methods: {
addNewTodo() {
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText
})
this.newTodoText = ''
}
}
})
app.component('todo-item', {
template: `
<li>
{{ title }}
<button @click="$emit('remove')">删除</button>
</li>
`,
props: ['title'],
emits: ['remove']
})
app.mount('#todo-list-example')
</script>
</body>
</html>