最近初学vue,做最简单的todolist
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>todolist</title> <style type="text/css"> #container{ 700px; height: 100px; padding: 40px; margin: 0 auto; } li{ list-style: none; } .close-btn{ display: inline-block; 20px; height: 20px; background: url('close.png') no-repeat; cursor: pointer; } .finished{ text-decoration: line-through; } </style> </head> <body> <div id="container"> <input type="text" v-model="newitem" @keyup.enter="addlistitem"/> <div class="todo-list"> <ul> <li v-for="(listitem,index) in list"> <input type="checkbox" v-model="listitem.isFinished" /> <span v-bind:class="{ finished: listitem.isFinished }" >{{ listitem.text }}</span> <span class="close-btn" @click="deleteitem(index)"></span> </li> </ul> </div> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script> var app = new Vue({ el: '#container', data: { newitem:'', list:[] }, watch: { // 如果 `list`数据 发生改变,这个函数就会运行 list: { handler:function () { this.saveTolocal(this.list) }, // 深度观察,当对象里的属性发生改变时,也会触发watch。点击checkbox需要deep: true,否则watch不会起作用。 deep: true } }, methods:{ // 添加项目 addlistitem:function(){ if(this.newitem != ''){ this.list.push({'text':this.newitem,'isFinished':false}) this.newitem = '' } }, // 删除项目 deleteitem:function(curIndex){ this.list.splice(curIndex,1) }, // 存入localStorage saveTolocal:function(data){ localStorage.setItem('tododata',JSON.stringify(data)) } } }); // 读取localStorage if(!!localStorage.getItem('tododata')){ app.list = JSON.parse(localStorage.getItem('tododata')) } </script> </body> </html>