todolist 案例
Header
<template>
<div class="todo-header">
<input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter="add"/>
</div>
</template>
<script>
//生成唯一字符串的库 调用即可
import { nanoid } from 'nanoid'
export default {
data() {
return {
title:''
}
},
methods: {
add() {
//如果输入框有输入 再添加
if (this.title) {
const todoObj = { id: nanoid(), title: this.title, done: false }
//调用APP传入的函数
this.addTodo(todoObj)
//添加后输入框为空
this.title=''
}
}
},
props:['addTodo']
}
Mylist组件
<template>
<ul class="todo-main">
<MyItem v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkTodo="checkTodo" :deletetodo="deletetodo"></MyItem>
</ul>
</template>
<script>
import MyItem from './MyItem.vue'
export default {
components: {
MyItem
},
props:['todos','checkTodo','deletetodo']
}
</script>
Myitem
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
<span>{{ todo.title }}</span>
</label>
<button class="btn btn-danger" @click="handledelete(todo.id)">删除</button>
</li>
</template>
<script>
export default {
props: ['todo', 'checkTodo','deletetodo'],
methods: {
handleCheck(id) {
//将对应id的done值取反 需要将获得的id传给APP 在APP中操作数据
this.checkTodo(id)
},
handledelete(id) {
if (confirm('确定删除吗?')) {
this.deletetodo(id)
}
}
}
}
</script>
Myfooter
<template>
<div class="todo-footer">
<label>
<input type="checkbox"/>
</label>
<span>
<span>已完成{{ doneTotal}}</span> / 全部{{ todos.length }}
</span>
<button class="btn btn-danger">清除已完成任务</button>
</div>
</template>
<script>
export default {
props: ['todos'],
computed: {
doneTotal() {
return this.todos.reduce((pre,todo) => {
return pre+ (todo.done ?1:0)
},0)
}
}
}
</script>
App
<template>
<div id="root">
<div class="todo-container">
<div class="todo-wrap">
<MyHeader :addTodo="addTodo"></MyHeader>
<MyList :todos="todos" :checkTodo="checkTodo" :deletetodo="deletetodo"></MyList>
<MyFooter :todos="todos"></MyFooter>
</div>
</div>
</div>
</template>
<script>
import MyHeader from './components/MyHeader.vue'
import MyList from './components/MyList.vue'
import MyFooter from './components/MyFooter.vue'
export default {
name: 'App',
components: {
MyHeader,
MyList,
MyFooter
},
data(){
return {
todos: [
{ id:'001',title:'打代码',done:true},
{id:'002',title:'睡觉',done:false},
{id:'003',title:'吃饭',done:true}
],
}
},
//增加一个todo
methods: {
addTodo(x){
this.todos.unshift(x)
},
//勾选 取消勾选一个todo
//将传入的id与现有的所有数据id作对比 遍历查找出是哪个id要进行操作
checkTodo(id) {
this.todos.forEach((todo) => {
if (todo.id == id) {
todo.done=!todo.done
}
})
},
//删除一个todo
deletetodo(id){
this.todos= this.todos.filter((todo) => {
return todo.id !== id
})
}
},
}