todomvc实现日程安排
1.启动案例
//定义vue实例挂载到window对象的app属性 //匿名函数 自调用 (function(exports){ exports.app=new Vue() })(windos)
2.业务拆分
<input id="toggle-all" class="toggle-all" type="checkbox" @change="handelToggleAll"> //根据change事件循环改变事件的完成状态 methods:{ handelToggleAll(e){ var checked=e.srcElement.checked //获取全选的状态 this.todos.forEach(item =>{ item.completed=checked }) } }<footer class="footer" v-show="todos.length"> <span class="todo-count"> <strong ></strong> </span> <ul class="filters"> <li><a href="#/all" >All</a></li> <li><a href="#/active" >Active</a></li> <li><a href="#/completed" >Completed</a></li> </ul> <button class="clear-completed"> </button> </footer><input class="new-todo" autofocus autocomplete="off" placeholder="What needs to be done?" v-model="newTodos" @keyup.enter="handleNewTodoKeyDown"> //事件处理函数 handleNewTodoKeyDown(){ //input 按下回车时添加新的数据 var value=this.newTodos && this.newTodos.trim() if(!value){ return } this.todos.push( { id:this.todos.length+1, title:value, completed:false} ) this.newTodos='' }<li class="todo" v-for="todo in todos" :key="todo.id" :class="{completed: todo.completed, editing: editedTodo == todo}"> <div class="view"> <input class="toggle" type="checkbox" v-model="todo.completed"> <label @dblclick="editTodo(todo)">{{todo.title}}</label> <button class="destroy" v-on:click="removeTodo(todo)"></button> </div> //用于修改的input <input class="edit" type="text" v-model="todo.title" > </li> 当点击修改时,原始数据进入隐藏状态,而修改按钮进行显示状态 这里主要得益于css选择器,当进入编辑状态时因为在li上增加了一个编辑类editTodo(todo){ this.beforeEditeTitle=todo.title this.editedTodo=todo }, cancleEdite(todo){ this.editedTodo = null; todo.title=this.beforeEditeTitle }, doneEdite(todo){ if(!this.editedTodo){ return } this.editedTodo=null todo.title=todo.title.trim() if(!todo.title){ this.removeTodo(todo) } }
//钩子对象 var filters={ all:function(todos){ return todos; }, active:function(todos){ return todos.filter(item=>!item.completed) }, completed:function(todos){ return todos.filter(item=>item.c) } } //计算属性 computed:{ reminds:function(){ return filters.active(this.todos).length } }//使用get访问计算属性,对todos的状态进行检查 toggleAllstat:{ get(){ //所有的都为true才为true return this.todos.every(todo=>(todo.completed)) } } //将计算属性绑定到标签上 <input id="toggle-all" class="toggle-all" type="checkbox" v-:checked="toggleAllstat">computed:{ reminds:function(){ return filters.active(this.todos).length }, toggleAllstat:{ get(){//访问计算属性时调用的方法 //所有的都为true才为true return this.todos.every(todo=>(todo.completed)) }, set(){ //当计算属性发生改变时进行调用 var checked=!this.toggleAllstat //获取变化后的值 this.todos.forEach(item =>{ item.completed=checked }) } } } <input id="toggle-all" class="toggle-all" type="checkbox" v-model="toggleAllstat">//本地化对象 var todoStorage={ fetch:function(){ return JSON.parse(exports.localStorage.getItem('todos-vuejs') || '[]'); }, save:function(todos){ exports.localStorage.setItem('todos-vuejs',JSON.stringify(todos)) } } data:{ todos:todoStorage.fetch(), },
Last updated