基于Vue的TodoList示例,麻雀虽小,五脏俱全css
Vue + localStorage + hashhtml
添加备忘录(输入标题后回车添加,若是内容为空或只有空格会清空,什么都不添加)vue
删除备忘录(点击标题后面的叉)git
完成备忘录(点击标题前面的复选框)github
编辑备忘录(双击标题进入编辑模式)npm
取消编辑备忘录(按ESC或者失去焦点时)vim
完成编辑备忘录(按回车键完成[若是内容为空的时候会自动删除],此时也会调用到失去焦点事件)数组
一键完成全部备忘录(点击第一行的复选框)mvc
过滤任务,显示所有,未完成,已完成的备忘录(点击所有,未完成,已完成按钮)app
清空已完成备忘录(点击清空已完成)
npm init -y
npm i -S underscore vue todomvc-app-css
vim index.html
复制格式化后的html
引入css
将英文标题换成中文标题
引入vue.js
新建vue的实例
写一个默认的任务:todoList: [{}]
// 新建一个Vue的实例对象 var todoapp = new Vue({ // 挂载 el: '.todoapp', // 数据 data: { // 备忘录数组 todoList: [ // 一个任务就是一个对象,text表示任务的名称,checked为true表示已完成,false表示未完成 { text: '学Vue', checked: false }, { text: '学React', checked: false } ] }, 方法 methods: { }, // 计算属性 computed: { } })
data: { newTodo: '', todos: todoStorage.fetch(), editedTodo: null, beforeEditCache: '', visibility }
computed: { //显示任务总数量 showTodos() { return this.todos.length > 0 }, //未完成 activeCount() { return filters.active(this.todos).length }, //已完成 completedCount() { return filters.completed(this.todos).length }, //判断全部任务 allDone: { get() { return this.activeCount === 0 }, set(value) { this.todos.map(todo => { todo.completed = value }) } }, //判断 filteredTodos() { return filters[this.visibility](this.todos) } }
//store.js的判断获取 (function(){ var STORAGE_KEY = 'todos' window.todoStorage = { fetch() { try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]') } catch(err) { return []; } }, save(todos) { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)) } } })();
var filters = { all: todos => todos, active: todos => todos.filter(todo => !todo.completed), completed: todos => todos.filter(todo => todo.completed) } var visibility = location.hash.substr(location.hash.indexOf('/')+1) visibility = visibility === '' ? 'all' : visibility watch: { todos: { deep: true, handler: todoStorage.save//判断当前应显示的内容 } }
methods: { addTodo() { this.newTodo = this.newTodo.trim() if (!this.newTodo) { return } this.todos.unshift({ title: this.newTodo, completed: false }) this.newTodo = '' }, removeTodo(todo) { var index = this.todos.indexOf(todo) this.todos.splice(index, 1) }, editTodo(todo) { this.editedTodo = todo this.beforeEditCache = todo.title }, doneEdit(todo) { if (!this.editedTodo) { return; } this.editedTodo = null; todo.title = todo.title.trim() if (!todo.title) { this.removeTodo(todo) } }, cancelEdit(todo) { if (this.editedTodo) { todo.title = this.beforeEditCache this.editedTodo = null } }, removeCompleted() { this.todos = filters.active(this.todos) } }
directives: { focus: { update(el) { el.focus() } } }