todolist-自定义组件
通过自定义组件改进todolist案例,不全使用prop方式
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 { name: "HeaderCom", // props:['addTodo'],//接受传入addTodo data(){ return{ title:''//收集用户输入的title } }, methods:{ add(){ //校验数据 if (!this.title.trim()) return alert("输入不能为空") //将输入包装成todo对象 const todoObj={id:nanoid(),title:this.title,done:false} //通知app组件添加一个todo对象 this.$emit('addTodo',todoObj) //清空输入 this.title='' } }, } </script>
footer
<template> <div class="todo-footer" v-show="total"> <label> <!-- <input type="checkbox" :checked="isAll" @change="checkAll"/>--> <input type="checkbox" :checked="isAll" @change="checkAll"/> </label> <span> <span>已完成{{doneTodo}}</span> / 全部{{total}} </span> <button class="btn btn-danger" @click="clearAll">清除已完成任务</button> </div> </template> <script> export default { name: "FooterCom", props: ['todoList'], computed:{ total() { return this.todoList.length }, doneTodo() { // return this.todoList.filter(todo => todo.done === true).length return this.todoList.reduce((pre,todo)=>pre+(todo.done ? 1 : 0),0) }, isAll() { return this.doneTodo === this.total && this.total > 0 } }, methods: { checkAll(e){ this.$emit('checkAllTodo', e.target.checked) // this.checkAllTodo(e.target.checked) }, clearAll() { if(confirm("确定清除吗?")){ this.$emit('clearAllTodo') // this.clearAllTodo() } } } } </script>
list与item还是使用prop传递双层消息
app
<template> <div id="app"> <div class="todo-container"> <div class="todo-wrap"> <HeaderCom @addTodo="addTodo"></HeaderCom> <ListCom :todoList="todoList" :checkTodo="checkTodo"></ListCom> <FooterCom :todoList="todoList" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"></FooterCom> </div> </div> </div> </template>
标签:return,自定义,title,todolist,day80,组件,total,todo From: https://www.cnblogs.com/GUGUZIZI/p/17163182.html