//存取localStorage中的数据
var store = {
// 添加信息到 localStorage 中
save:function(key,value){
localStorage.setItem(key,JSON.stringify(value));
},
// 取出 localStorage 数据
fetch:function(key){
return JSON.parse(localStorage.getItem(key)) || [];
}
}
// 取出所有的值
var list = store.fetch("lichi-todo-class");
// 将其封装为一个对象
var filter = {
all:function(list){
return list;
},
finished:function(list){
return list.filter(function(item){
return item.isChecked;
});
},
unfinished:function(list){
return list.filter(function(item){
return !item.isChecked;
});
},
}
var vm = new Vue({
el: ".main",
data: {
list:list,
todo:"",
isView:'', //记录正在编辑的数据
beforeTitle:'', //记录正在编辑的数据的title
visibility: "all" //通过这个属性值的变化对数据进行筛选
},
// 选项对象
computed: {
//计算属性
noCheke:function(){
//过滤操作
return this.list.filter(function(item){
return !item.isChecked;
}).length
},
filteredList:function(){
return filter[this.visibility] ? filter[this.visibility](list) : list;
},
},
//集中管理事件响应
methods: {
//当不传递参数时,默认传递为 事件对象,有传递参数时需要另外用参数接收
//addTodo:function(date, ev)
addTodo: function() { //添加任务 ES6 时可以简写,ES 5 不行
//健壮性判断
if(this.todo === '') {
return;
}
//向list 中添加元素对象
//事件处理函数中的this 指向的是当前这个跟实例
this.list.push({
// title:ev.target.value //操作DOM
title: this.todo,
isChecked: false,
isView: '',
isInp: false,
beforeTitle: '',
});
this.todo = '';
},
deleteTodo: function(todu) { //删除任务
var index = this.list.indexOf(todu);
this.list.splice(index, 1);
},
edtorTodo: function(todo) { //编辑任务
todo.isInp = true;
this.isView = todo;
//编辑前先存储该值
this.beforeTitle = todo.title;
},
edtorTodoed: function(todu) { //编辑任务成功
todu.isInp = false;
},
cancelTodo: function(todu) { //编辑取消
todu.title = this.beforeTitle;
todu.isInp = false;
console.log(this.beforeTitle);
},
},
// 自定义指令
directives: {
"focuse": {
update: function(el, binding) {
if(binding.value) {
el.focus();
}
}
}
}
});
function watch(){
var hash = window.location.hash.slice(1);
vm.visibility = hash;
}
watch();
//addEventListener() 方法用于向指定元素添加事件句柄。
window.addEventListener("hashchange", watch);