1. 拆分基础组件
<template>
<!-- 主体区域 -->
<section id="app">
<!-- 输入框 -->
<TodoHeader ></TodoHeader>
<!-- 列表框 -->
<TodoMain ></TodoMain>
<!-- 统计和清空 -->
<TodoFooter></TodoFooter>
</section>
</template>
<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
data() {
return {
}
},
components: {
TodoHeader,
TodoMain,
TodoFooter,
},
}
</script>
2. 渲染代办任务
思路分析:
- 提供数据:提供在公共的父组件 App.vue
- 通过父传子,将数据传递给TodoMain
- 利用v-for进行渲染
<!-- 列表框 -->
<TodoMain :list="list"></TodoMain>
data() {
return {
list:[
{id:1,name:"吃饭"},
{id:2,name:"睡觉"},
{id:3,name:"打豆豆"},
]
}
},
<!-- 列表区域 -->
<section class="main">
<ul class="todo-list">
<li class="todo" v-for="(item, index) in list" :key="item.id">
<div class="view">
<span class="index">{{index + 1}}.</span>
<label>{{item.name}}</label>
<button class="destroy"></button>
</div>
</li>
</ul>
</section>
<script>
export default {
props: ['list']
}
</script>
3. 删除功能
思路分析:
- 监听时间(监听删除的点击)携带id
- 子传父,将删除的id传递给父组件App.vue
- 进行删除 filter (自己的数据自己负责)
<button class="destroy" @click="$emit('del', item.id)"></button>
<!-- 列表框 -->
<TodoMain :list="list" @del="handleDel"></TodoMain>
handleDel(id) {
this.list = this.list.filter(item => item.id !== id)
}
4. 添加功能
思路分析:
- 收集表单数据 v-model
- 监听时间 (回车+点击 都要进行添加)
- 子传父,将任务名称传递给父组件App.vue
- 父组件接受到数据后 进行添加 unshift(自己的数据自己负责)
<button class="add" @click="post">添加任务</button>
methods: {
post() {
// $emit写到js区,要用this.$emit();this.todoname
this.$emit('add', this.todoname) // 子传父语法
this.todoname = '' // 清空输入框
}
}
<!-- 输入框 -->
<TodoHeader @add="handleAdd"></TodoHeader>
methods: {
handleAdd(todoname) {
this.list.unshift({ id: Date.now(), name: todoname })
}
}
5. 合计和清空
思路分析:
- 底部合计:父组件传递list到底部组件 —>展示合计
<!-- 统计和清空 -->
<TodoFooter :list="list" @clear="list = []"></TodoFooter>
<script>
export default {
props:['list'],
}
</script>
<!-- 统计 -->
<span class="todo-count">合 计:<strong> {{list.length}} </strong></span>
- 清空功能:监听事件 —> 子组件通知父组件 —>父组件清空
<!-- 清空 -->
<button class="clear-completed" @click="$emit('clear')">清空任务</button>
<!-- 统计和清空 -->
<TodoFooter :list="list" @clear="list = []"></TodoFooter>
5. 持久化存储
思路分析:
- 持久化存储:watch监听数据变化,持久化到本地
export default {
data() {
return {
list: JSON.parse(localStorage.getItem('todoList')) || [
{ id: 1, name: "吃饭" },
{ id: 2, name: "睡觉" },
{ id: 3, name: "打豆豆" },
]
}
},
}
watch: {
// list(val) {
// localStorage.setItem('todoList', JSON.stringify(val))
// }
list: {
handler(val) {
localStorage.setItem('todoList', JSON.stringify(val))
},
deep:true
}
}
网友评论