这是第一次跟着老师学Vuejs,以前看官方文档很多不懂,现在做了一个小例子:
效果图如下:
代码如下:
HTML:
1 2 3 4 5每天进步清单 6 7 8 91014 55 56 57 58 591113任务计划列表
12
JS如下:
1 /* 2 *author:黄文锋; Email:915581960@qq.com; 3 *create time: 2017/4/19 4 */ 5 6 //存取localStorage中的数据 7 8 var store = { 9 save(key,value){ 10 localStorage.setItem(key,JSON.stringify(value)); 11 }, 12 fetch(key){ 13 return JSON.parse(localStorage.getItem(key)) || []; 14 } 15 } 16 17 18 19 //取出所有的值 20 var list = store.fetch("mydata"); 21 22 //过滤的时候有三种情况 all finished unfinished 23 24 var filter = { 25 all:function(list){ 26 return list; 27 }, 28 finished:function(list){ 29 return list.filter(function(item){ 30 return item.isChecked; 31 }) 32 }, 33 unfinished:function(){ 34 return list.filter(function(item){ 35 return !item.isChecked; 36 }) 37 } 38 } 39 40 var vm = new Vue({ 41 el:".main", 42 data:{ 43 list:list, 44 todo:"", 45 edtorTodos:'', //记录正在编辑的数据 46 beforeTitle:'', //记录正在编辑的数据的title 47 visibility: "all" //通过这个属性值的变化对数据进行筛选 48 }, 49 watch:{ 50 list:{ 51 handler:function(){ 52 store.save("mydata",this.list); 53 }, 54 deep:true 55 } 56 }, 57 computed:{ 58 noCheckeLength:function(){ 59 return this.list.filter(function(item){ 60 return !item.isChecked 61 }).length 62 }, 63 filteredList:function(){ 64 //找到了过滤函数,就返回过滤后的数据;如果没有返回所有数据 65 return filter[this.visibility] ? filter[this.visibility](list) : list; 66 67 } 68 }, 69 methods:{ 70 addTodo(){ //添加任务 71 this.list.push({ 72 title:this.todo, 73 isChecked:false 74 }); 75 this.todo = ''; 76 77 }, 78 deleteTodo(todo){ //删除任务 79 var index = this.list.indexOf(todo); 80 this.list.splice(index,1); 81 82 }, 83 edtorTodo(todo){ //编辑任务 84 console.log(todo); 85 //编辑任务的时候,记录一下编辑这条任务的title,方便在取消编辑的时候重新给之前的title 86 this.beforeTitle = todo.title; 87 88 this.edtorTodos = todo; 89 90 91 92 }, 93 edtorTodoed(todo){ //编辑任务成功 94 this.edtorTodos = ''; 95 }, 96 cancelTodo(todo){ //取消编辑任务 97 98 todo.title = this.beforeTitle; 99 100 this.beforeTitle = '';101 102 //让div显示出来,input隐藏103 this.edtorTodos = '';104 }105 },106 directives:{107 "foucs":{108 update(el,binding){109 if(binding.value){110 el.focus();111 }112 }113 }114 }115 });116 117 function watchHashChange(){118 var hash = window.location.hash.slice(1);119 120 vm.visibility = hash;121 122 }123 124 watchHashChange();125 126 window.addEventListener("hashchange",watchHashChange);
很粗糙的例子,后续还会继续完善......