<template>
<div id="container">
<div id="parent">
<TodoHeader @addTodo="addTodo" />
<TodoList :todos="todos" :removeTodo="deleteTodo" />
<TodoFooter
:finish="finish"
:all="all"
:clear="clear"
:doneAll="doneAll"
/>
</div>
</div>
</template>
<script>
import TodoFooter from "./TodoFooter.vue";
import TodoHeader from "./TodoHeader.vue";
import TodoList from "./TodoList.vue";
export default {
name: "TodoComponent",
components: {
TodoFooter,
TodoHeader,
TodoList,
},
data() {
return {
todos: [],
};
},
mounted() {
let arr = JSON.parse(localStorage.getItem("todos"));
if (arr === null) {
arr = [];
}
this.todos = arr;
//放入全局事件总线
this.$bus.$on('removeTodo',this.deleteTodo);
},
beforeDestroy(){
this.$bus.$off('removeTodo');
},
methods: {
addTodo(x) {
console.log("我是Todo组件,我收到了数据", x);
this.todos.unshift(x);
},
clear() {
console.log("清除了");
const idList = this.todos.filter((x) => x.done).map((x) => x.id);
for (let i = 0; i < this.todos.length; i++) {
if (idList.includes(this.todos[i].id)) {
this.todos.splice(i, 1);
i--;
}
}
console.log(this.todos);
},
doneAll(choose) {
this.todos.forEach((x) => (x.done = choose));
},
deleteTodo(id) {
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].id === id) {
console.log(i, "下标");
break;
}
}
this.todos.splice(i, 1);
},
},
computed: {
finish() {
return this.todos.filter((x) => x.done).length;
},
all() {
return this.todos.length;
},
},
watch:{
todos:{
deep:true,
handler(value){
localStorage.setItem("todos", JSON.stringify(value));
}
}
}
};
</script>
<style scoped>
#parent {
width: 600px;
border: 1px solid #ccc;
display: flex;
justify-content: center; /* 水平居左 */
align-items: center; /* 垂直居中 */
flex-direction: column; /* 垂直排列子元素 */
}
#parent > * {
margin: 10px 0px;
}
</style>