todolist的效果图
js代码
// localStorage存储
var todostorage = {
fetch () {
return JSON.parse(localStorage.getItem('vue-mvc') || '[]')
},
save (todos) {
localStorage.setItem('vue-mvc',JSON.stringify(todos))
}
};
// 根据hash变化更新todos
var filters = {
all (todos) {
return todos;
},
active (todos) {
return todos.filter(function(todo){
return !todo.completed
})
},
completed(todos) {
return todos.filter(function(todo){
return todo.completed
})
}
}
// 监听hash变化
window.addEventListener('hashchange',function(){
var hash = window.location.hash.slice(1);
app.visibility = hash;
})
var app = new Vue({
el: ".main",
data: {
todos: todostorage.fetch(),
newTodo:'',
editedTodo: null,
visibility: 'all'
},
watch: {
todos: {
deep: true,
handler: todostorage.save
}
},
computed: {
filtersTodo(){
return filters[this.visibility]? filters[this.visibility](this.todos) : this.todos
},
remainingTodos(){
return filters['active'](this.todos).length;
}
},
methods: {
addTodo () {
var value = this.newTodo && this.newTodo.trim();
if(!value){
return
}
this.todos.push({
title: value,
completed: false
});
this.newTodo = ""
},
removeTodo (todo) {
var index = this.todos.indexOf(todo);
this.todos.splice(index,1)
},
editTodo (todo) {
this.todoBefore = todo.title;
this.editedTodo = todo;
},
doneEdit (todo) {
this.editedTodo = null;
todo.title = todo.title.trim();
if(!todo.title){
this.removeTodo(todo)
}
},
cancelEdit (todo){
this.editedTodo = null;
todo.title = this.todoBefore;
}
},
directives: {
'todo-focus': function(el,binding){
if(binding.value){
el.focus();
}
}
}
})