看到非常多的Vue.js入门问答及教程,都有提到做一个TodoList的Demo,所以我就跟着教程写了一遍,然后不看教程再自己写一个,增加了未完成排到前面的小功能(其实就是数组的sort()排序<{=..)。同样的,数据依然直接采用localStorage储存,写完感觉Vue.js数据双向绑定挺不错,不需要操作DOM。
代码如下:
- <div id="app">
- <div>
- <input type="text" class="addInput" placeholder="请输入待办事项" v-model="todo.content" @keydown.enter="addTodo">
- </div>
- <div class="unit" v-for="(item,index) in lists">
- <input type="checkbox" class="cb" :checked="item.finished" @click="changeStatus(index)">
- <span :class="{'finish':item.finished,'no':true}">{{index+1}}</span>
- <span :class="{'finish':item.finished,'con':true}">{{item.content}}</span>
- <button type="button" class="delBtn" @click="delItem(index)">×</button>
- </div>
- <div class="empty" v-if="lists.length === 0">
- 暂无内容!
- </div>
- </div>
- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
- <script>
- var ls = window.localStorage;
- var lsLists = new Array();
- if (ls.getItem("lists") != null) {
- //从localStorage取出JSON字符串,并转为对象
- lsLists = JSON.parse(ls.getItem("lists"));
- }
- var vm = new Vue({
- el: '#app',
- data: {
- lists:lsLists,
- todo:{
- content:'',
- finished:false,
- deleted:false
- }
- },
- methods:{
- //添加
- addTodo(){
- this.lists.unshift(this.todo);
- //根据完成状况排序
- this.lists.sort(sortF);
- //将对象转为JSON字符串
- ls.setItem("lists",JSON.stringify(this.lists));
- this.todo = {
- content : '',
- finished:false,
- deleted:false
- };
- },
- //改变状态
- changeStatus(i){
- let thisStatus = this.lists[i].finished;
- //状态翻转
- this.lists[i].finished = !thisStatus;
- //根据完成状况排序
- this.lists.sort(sortF);
- //将对象转为JSON字符串
- ls.setItem("lists",JSON.stringify(this.lists));
- },
- //删除
- delItem(i){
- //删除当前index=i的一条
- this.lists.splice(i,1);
- //将对象转为JSON字符串
- ls.setItem("lists",JSON.stringify(this.lists));
- }
- }
- });
- function sortF(a,b){
- console.log(a.finished,b.finished)
- return a.finished-b.finished;
- }
- <script>