vue3 TodoLists 父子组件传递
App.vue
<template>
<Header :/>
<List :todos="todos" :addTodo="addTodo" />
<Footer :todos="todos" :checkAll =“checkAll ” :clearAllChecked =“clearAllChecked ”/>
</template>
import {defineComponent} from 'vue'
import { Todo } from '../types/todo.ts'
export defineComponent{
name:'App',
components:{
Header,
List,
Footer
},
setup(){
return{
//定义一个数组数据
const state = reactive<todos: Todo []>({
todos:[
{
id:1,title:'奔驰',isCompleted:false
},
{
id:2,title:'宝马',isCompleted:true
},
{
id:3,title:'奥迪',isCompleted:false
}
]
})
//添加TodoList数据
const addTodo =(Todo:Todo)=>{
const Todo = state.todos.unshift(Todo)
}
const checkAll = (isCompleted:boolean)=>{
state.todos.forEach((todo)=>{
todo.isCompleted = isCompleted
})
}
//清理所有选中数据
const clearAllChecked = ()=>{
state.todos = state.todos.filter((todo)=> !todo.isCompleted)
}
return{
...toRefs(state),
addTodo ,
checkAll
}
}
}
}
Footer.vue
<template>
<div>
<label>
<input type="checkbox" v-model="isCheckAll"/>
</label>
<span><span>已完成{{ count }}</span>/全部{{ todos.lenth}}</span>
<button @click="clearAllChecked ">清除已完成任务</button>
</div>
</template>
<script lang="ts">
import {defineComponent} from 'vue'
import { Todo } from '../tyes/todo'
export default defineComponent ({
name:'Footer',
props:{
todos:{
type:Array as()=>Todo[],
required:true
},
checkAll:{
type:Function,
required:true
},
clearAllChecked :{
type:Function,
required:true
}
},
setup(props){
const count = computed(()=>{
return props.todos.reduce((pre,todo,index)=> pre+(todo.isCompleted?1:0),0)
})
const isCheckAll = computed({
get(){
return count.value>0 && props.todos.length == count.vlaue
},
set(val){
props.checkAll(val)
}
})
},
return{
count
}
})
</script>
|