组件化实现todoList
App.vue
<template>
<div>
<Header :addTodo="addTodo"></Header>
<Main :todos="todo" @handleCheck="handleCheck" @del="delClick"></Main>
<Footer :todos="todo" @checkAll="checkAll"></Footer>
</div>
</template>
<script>
import Footer from "@/components/Footer";
import Header from "@/components/Header";
import Main from "@/components/Main";
export default {
name: "Index",
components:{Footer,Header,Main},
data(){
return {
todo:[
// {id:new Date().getTime(),title:'吃饭',done:false}
]
}
},
methods:{
addTodo(item){
console.log (item)
this.todo.push(item)
},
//选中checked
handleCheck(id){
this.todo.filter(item=>{
if (item.id==id){
item.done=!item.done
}
})
},
checkAll(checked){
console.log (checked)
this.todo.filter(item=>item.done=checked)
},
delClick(id){
//这里使用filter进行过滤,会返回一个新的数组,需要将新的数组赋值给todo
let list=this.todo.filter(item=>item.id!==id)
this.todo=list
console.log (list)
// this.todo.splice(id, 1)
}
}
}
</script>
<style scoped>
</style>
这里包含了组件之间的传值:父组件向子组件传值通过动态绑定属性的方式,props:的值可以是字符串,可以是数组,也可以是函数,
在子组件中,通过props:[‘’],进行接收。
Header.vue
<template>
<div>
<h1>todoList</h1>
<input type="text" placeholder="请输入任务" v-model="title"/>
<button @click="handle">添加</button>
</div>
</template>
<script>
export default {
name: "Header",
//父组件可以向子组件传递字符,数组 函数
props:['addTodo'],
data(){
return {
title:''
}
},
methods:{
handle(){
if (!this.title.trim()) return
const todoObj={id:new Date().getTime(),title:this.title,done:false}
this.addTodo(todoObj)
this.title=''
}
}
}
</script>
<style scoped>
</style>
这里通过props:[‘addTodo’],接受父组件中传过来的函数,通过
const todoObj={id:new Date().getTime(),title:this.title,done:false}
将要添加的对象,回传给父组件
this.addTodo(todoObj),
Main.vue
<template>
<div>
<ul>
<li :key="item.id" v-for="item in todos">
<input type="checkbox" v-model="item.done" @click="handleChecked(item.id)"/>
{{ item.title }}
<button @click="del(item.id)">删除</button>
</li>
</ul>
{{ this.todos.length==0?'无数据':'' }}
</div>
</template>
<script>
export default {
name: "Main",
props:['todos'],
data(){
return {
}
},
methods:{
handleChecked(id){
this.$emit('handleCheck',id)
},
del(id){
this.$emit('del',id)
}
}
}
</script>
<style scoped>
</style>
在此组件中,通过props:[‘todos’],接受父组件传来的todos数组
Footer.vue
<template>
<div>
全选:<input type="checkbox" v-model="checked" @click="checkAll()">
<span>已完成{{ active }}/总数{{ all }}</span>
</div>
</template>
<script>
export default {
name: "Footer",
props:['todos'],
data(){
return {
checked:false
}
},
computed:{
active(){
return this.todos.filter(item=>item.done==true).length
},
all(){
return this.todos.length
}
},
methods:{
checkAll(){
console.log (!this.checked)
this.$emit('checkAll',!this.checked)
}
}
}
</script>
<style scoped>
</style>
获取父组件的props:[‘todos’]