一、项目介绍
①地址:http://todomvc.com/
②GitHub下载模板
③通过npm下载模板的样式
④通过npm下载Vuejs
⑤项目文件,主要修改app.js和index.html两个文件
二、使用Vuejs需求实现
①列表渲染
- 有数据的时候展示出来:v-if 的使用
(function (Vue) { let todos=[ {id:1,title:'睡觉',completed:true}, {id:2,title:'美食',completed:false}, {id:3,title:'代码',completed:true} ] new Vue({ el:'#todoapp', data:{ todos:todos, }, })(Vue);
<li v-for="item of todos" v-bind:class='{completed:item.completed}'> <div class="view"> <input class="toggle" type="checkbox" v-model='item.completed'> <label>{{item.title}}</label> <button class="destroy"></button> </div> <input class="edit" value="Create a TodoMVC template"> </li>
- 没有数据的时候隐藏main部分:添加一个不会出现在页面的template模板,并且使用v-if,当todos没有数据的时候,长度为0
<template v-if='todos.length'> <!-- This section should be hidden by default and shown when there are todos --> <section class="main"> ..... </section> <!-- This footer should hidden by default and shown when there are todos --> <footer class="footer"> .... </footer> </template>
②添加任务
- 页面初始化获得焦点
- 敲回车添加到任务列表:鼠标抬起注册addTodo事件,追加数据
- 不允许有非空数据:为空时,return返回
- 添加完成后清空文本框:令event.target.value= ' '
<header class="header"> <h1>todos</h1> <input class="new-todo" placeholder="What needs to be done?" @keyup.enter='addTodo'> </header>
methods:{ // 添加任务 addTodo(event){ let todoText=event.target.value.trim(); if(!todoText.length){ return } let id=this.todos[this.todos.length-1].id+1; this.todos.push({ id:id, title:todoText, completed:false, }); event.target.value=''; },
③标记所有任务完成或者未完成:点击的时候注册toggleAll事件处理函数
<input @click='toggleAll' id="toggle-all" class="toggle-all" type="checkbox">
toggleAll(event){ let checked=event.target.checked; this.todos.forEach(todo => todo.completed=checked); },
④任务项
- 切换任务完成状态:v-bind绑定一个class,根据完成状态的变化而变化
<li v-for="item of todos" v-bind:class='{completed:item.completed}'>
⑤
⑥