Vue2.0 Todolist 源码解析 【localStorage+Vue2.0】

466 阅读5分钟

1.分析整个todolist功能

图解

image.png

image.png


1.双箭头表示主干上的流程
2.单箭头表示所依附的出发点内部的流程,第二张图是第一张图中单箭头的延续
3.图一左上角是根据页面内容细分出来的html结构

功能分析

  • 添加todo项
  • 删除todo项
  • 修改todo项
  • 完成todo项
  • 一键删除完成的todo项
  • 按类别显示todo项
  • 显示剩余todo项总数

2.代码分析

2.1 Html的body部分

header部分
        <section class="todoapp">
            <header class="header">
                <h1>todos</h1>
                <input class="new-todo" autofocus autocomplete="off" placeholder="待办事项" v-model="newTodo" @keyup.enter="addTodo">
            </header>
main部分
            <!-- v-cloak可以解决查值表达式闪烁的问题 -->
            <section class="main" v-show="todos.length" v-cloak>
                <!-- v-model 实现数据的双向绑定 -->
                <!-- allDone:一摁下这个checkbox,则向allDone传递true值 -->
                <input class='toggle-all' type="checkbox" v-model='allDone'>
                <ul class="todo-list">
                    <!-- class的解释:如果todo.completed为true则执行completed效果;如果todo==editedTodo,表示正在修改中,则执行editing效果 -->
                    <!-- v-for保证了li只呈现fliteredTodo里面的内容 -->
                    <li v-for="todo in filteredTodos" class="todo" :key="todo.id" :class="{completed:todo.completed,editing:todo==editedTodo}">
                        <div class="view">
                            <!-- 用户交互:todo是否完成 -->
                            <input type="checkbox" class="toggle" v-model="todo.completed">
                            <!-- 用户交互:双击修改todo内容 -->
                            <label @dblclick="editTodo(todo)">{{todo.title}}</label>
                            <!-- 用户交互:直接删除一个todo -->
                            <button class="destroy" @click="removeTodo(todo)"></button>
                        </div>
                        <!-- 这是一个隐藏的input框,在editing时才会出现,它与todo.title双向绑定 -->
                        <!-- @blur是当元素失去焦点时,在这里就是todo.title失去焦点时 -->
                        <!-- 键盘功能:编辑时,按下Esc键,则取消更改 -->
                        <!-- BUG:keyup事件触发后,blur也会被触发,所以二者不可以绑定到同一个功能上。解决方法:使用keyup事件触发blur事件 -->
                        <!-- BUG:enter之后,todo还是有css的框选效果,考虑用户交互体验应当在enter后取消框选效果 -->
                        <!-- BUG:当input框为空时,应当删除todo=>editedTodo为空,在doneEdit里面直接return了,没有进行后面remove的操作-->
                        <input type="text" class="edit"
                            v-model="todo.title"
                            v-todo-focus="todo == editedTodo"
                            @blur="doneEdit(todo)"
                            @keyup.enter="$event.target.blur"
                            @keyup.esc="cancelEdit(todo)">
                    </li>
                </ul>
            </section>
footer部分
            <footer class="footer">
                <span class="todo-count">
                    <!-- pluralize与remaining一样,都是app实例中的一个属性 -->
                    <strong>{{remaining}}</strong> {{remaining|pluralize}} left
                </span>
                <ul class="filters">
                    <li><a href="#/all" :class="{selected:visibility=='all'}">All</a></li>
                    <li><a href="#/active" :class="{selected:visibility=='active'}">Active</a></li>
                    <li><a href="#/completed" :class="{selected:visibility=='completed'}">Completed</a></li>
                </ul>
                <button class="clear-completed" @click="removeCompleted" v-show="todos.length > remaining">Clear Completed</button>
            </footer>
        </section>

2.2 Vue.js内容

window.onload=function(){……}

将所有的BOM和DOM操作放在里面,onload保证了里面的代码时在html的body页面加载完成后进行的,所以script可以位于页面的任何位置;

var STORAGE_KEY = 'todos-vuejs-2.0'
                var todoStorage = {
                    fetch:function(){
                        var todos = JSON.parse(localStorage.getItem(STORAGE_KEY)||'[]')
                        todos.forEach(function(todo,index){
                            todo.id = index
                        })
                        todoStorage.uid = todos.length
                        return todos
                    },
                    save: function (todos) {
                        localStorage.setItem(STORAGE_KEY,JSON.stringify(todos))
                    }
                }

以上是BOM操作,与浏览器的localSotrage进行交互,将整个todos的数据都保存在local中。 fetch:取出存储在local中的todos,并且把每个todo的内容都整理罗列好 save:把整个todos存入local中,这个操作在每一次todo改动时都会重复操作

var filters = {
                    all: function(todos){
                        return todos
                    },
                    active:function(todos){
                        return todos.filter(function(todo){
                            return !todo.completed
                        })
                    },
                    completed:function(todos){
                        return todos.filter(function(todo){
                            return todo.completed
                        })
                    }
                }//.filter():是js原生方法,为数组中每个元素调用回调函数,
                //并将所有所有使得 callback 返回 true的值 的元素创建一个新数组。

filters是全局变量,在其中对todos进行了分类。
里面的属性届时用[visibility]表示并筛选,因为该属性涉及到BOM操作,所以独立于实例存在。

                //实例
                var app = new Vue({
                    //实例初始状态
                    //初始时候visibility是all
                    //todos也是从storage取出的热乎值
                    data:{
                        todos:todoStorage.fetch(),
                        newTodo: '',
                        editedTodo: null,
                        visibility: 'all'
                    },
                    //监听属性
                    watch:{
                        todos:{
                            handler:function(todos){
                                todoStorage.save(todos)
                            },
                            deep:true
                        }
                    },//handler方法:当数据变化时候执行的操作
                    //imediate:true是在默认状态下也执行操作
                    //deep:true深度监听,可以监听对象内部属性的改变
                  //计算属性,必须要有return值,适用于需要实时变化的属性值或是checkbox传递值进来
                    computed:{
                        filteredTodos:function(){//对todos执行filters方法
                            return filters[this.visibility](this.todos)
                        },
                        remaining:function(){//剩余未完成的todo
                            return filters.active(this.todos).length
                        },
                        allDone:{
                            get:function(){//将未完成的todo全部干掉
                                return this.remaining === 0
                            },
                            set:function(value){//把每一个todo的属性completed设为传入值,就是true
                                this.todos.forEach(function(todo){
                                    todo.completed=value
                                })
                            }
                            }
                        },
                    //包含Vue实例中可用过滤器的哈希表 {{xx|pluralize}}
                    filters:{
                        pluralize:function(n){
                            return n === 1 ? 'item':'items'
                        }
                    },

                     //方法 事件触发后执行这个操作,如@click@blur@keyupinput框之类的
                    methods:{
                        addTodo: function(){
                            var value = this.newTodo && this.newTodo.trim()
                            if(!value){//表示结束函数调用,返回调用处,什么都不返回
                                return
                            }
                            this.todos.push({
                                id:todoStorage.uid++,
                                title:value,
                                completed:false
                            })
                            this.newTodo = '';
                        },
                        removeTodo: function(todo){
                            //把所对应的todo从todos里删去
                            this.todos.splice(this.todos.indexOf(todo),1)
                        },
                        editTodo: function(todo){
                            this.beforeEditCache=todo.title
                            this.editedTodo = todo
                        },
                        doneEdit: function(todo){
                            if(!todo.editedTodo){
                                return
                            }
                            this.editedTodo = null;
                            todo.title = todo.title.trim();
                            if(!todo.title){
                                //如果内容为空,则删除todo
                                this.removeTodo(todo)
                            }
                        },
                        cancelEdit:function(todo){
                            this.editedTodo=null
                            todo.title=this.beforeEditCache
                        },
                        removeCompleted:function(){
                            // 重新赋值todos的内容
                            this.todos=filters.active(this.todos)
                        }
                    },
                    //自定义组件——钩子函数:包含Vue实例中可用指令的哈希表
                    //el: 指令所绑定的元素,可以用来直接操作 DOM 。
                    // binding: 一个对象,包含以下属性:
                    // name: 指令名,不包括 v- 前缀。这里为todo-focus
                    // value: 指令的绑定值,此处v-todo-focus="todo == editedTodo",value值是该表达式的true或false
                    //这个组件时判断todo是否等于editedTodo,也就是双击之后立即focus,而且它只调用一次,
                    //指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
                    directives:{
                        'todo-focus':function(el,binding){
                            if(binding.value){
                                el.focus()
                            }
                        }
                    }
                })

以上都是实例App的内容。

                //window.location.hash可以获取url的hash值(#/xxxx),hash值在footer中随着href改变
                function onHashChange() {
                    var visibility = window.location.hash.replace(/#\/?/,'')
                    //filters中的visibility上面hash中获取到的
                    if(filters[visibility]){
                        app.visibility=visibility
                        //上面的=visibility是此方法中创建的var
                    }else{
                        window.location.hash=''
                        app.visibility='all'
                    }
                }
                //一旦地址栏的hash改变,就进行onHashChange
                window.addEventListener('hashchange',onHashChange)
                onHashChange()

这是一个BOM操作,与url的值进行交互。

                // 在实例挂载之后,元素可以用 vm.$el 访问。
                //如果在实例化时el,实例将立即进入编译过程,否则,需要显式调用 vm.$mount() 手动开启编译。
                app.$mount('.todoapp')
            }

到这里script的内容就结束了。

2.3 css内容

/* 元素选择器 */
html,
body {
	margin: 0;
	padding: 0;
}

button {
	position: relative;
	margin-left: 0;
	padding: 0;
	border: 0;
	background: none;
	font-size: 20px;
	vertical-align: baseline;
	font-family: inherit;
	font-weight: inherit;
	color: rgba(175, 47, 47, 0.15);
	-webkit-appearance: none;
	appearance: none;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}
/* -webkit-font-smoothing:对字体的锯齿进行调整 */
/* -moz-osx-font-smoothing: inherit | grayscale=》Gecko内核的浏览器火狐,针对ios系统制定了一个渲染规则 */
/* IELT中,复选框选中了没有打钩,是由于css中“-webkit-appearance: none;”导致的,改成“-webkit-appearance: checkbox”后恢复正常。 */
/* 所有主流浏览器都不支持 appearance 属性。
   Firefox 支持替代的 -moz-appearance 属性。
   Safari 和 Chrome 支持替代的 -webkit-appearance 属性。 */
body {
	font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
	line-height: 1.4em;
	background: #f5f5f5;
	color: #4d4d4d;
	min-width: 230px;
	max-width: 550px;
	margin: 0 auto;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	font-weight: 300;
}
/* max和min-width可以限制元素的最大最小,在调整页面大小的时候,有一个极限变动区间,有助于响应式页面 */
/* margin:0 auto=》上下外边距为0,左右自动,实际效果为左右居中 */

/* 伪元素选择器 */
/* focus时,整个input的css设计 */
:focus {
	outline: 0;
}
/* outline属性与focus状态和键盘访问关系密切,功能上类似border */

/* 类选择器 */
.hidden {
	display: none;
}

.todoapp {
	background: #fff;
	margin: 130px 0 40px 0;
	position: relative;
	box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
	            0 25px 50px 0 rgba(0, 0, 0, 0.1);
}

.todoapp input::-webkit-input-placeholder {
	font-style: italic;
	font-weight: 300;
	color: #e6e6e6;
}

.todoapp input::-moz-placeholder {
	font-style: italic;
	font-weight: 300;
	color: #e6e6e6;
}

.todoapp input::input-placeholder {
	font-style: italic;
	font-weight: 300;
	color: #e6e6e6;
}

.todoapp h1 {
	position: absolute;
	top: -155px;
	width: 100%;
	font-size: 100px;
	font-weight: 100;
	text-align: center;
	color: rgba(175, 47, 47, 0.15);
	-webkit-text-rendering: optimizeLegibility;
	-moz-text-rendering: optimizeLegibility;
	text-rendering: optimizeLegibility;
}

.new-todo,
.edit {
	position: relative;
	margin: 0;
	width: 100%;
	font-size: 24px;
	font-family: inherit;
	font-weight: inherit;
	line-height: 1.4em;
	border: 0;
	color: inherit;
	padding: 6px;
	border: 1px solid #999;
	box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
	box-sizing: border-box;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.new-todo {
	padding: 16px 16px 16px 60px;
	border: none;
	background: rgba(0, 0, 0, 0.003);
	box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}

.main {
	position: relative;
	z-index: 2;
	border-top: 1px solid #e6e6e6;
}
/* 属性选择器 */
label[for='toggle-all'] {
	display: none;
}

.toggle-all {
	position: absolute;
	top: -55px;
	left: -12px;
	width: 60px;
	height: 34px;
	text-align: center;
	border: none; /* Mobile Safari */
}

.toggle-all:before {
	content: '❯';
	font-size: 22px;
	color: #e6e6e6;
	padding: 10px 27px 10px 27px;
}

.toggle-all:checked:before {
	color: #737373;
}

.todo-list {
	margin: 0;
	padding: 0;
	list-style: none;
}

.todo-list li {
	position: relative;
	font-size: 24px;
	border-bottom: 1px solid #ededed;
}

.todo-list li:last-child {
	border-bottom: none;
}

/* 进行editing时,整个li底部的border会消失 */
.todo-list li.editing {
	border-bottom:none;
	padding: 0;
}
/* 当进行edit过程时,显示input框 */
.todo-list li.editing .edit {
	display: block;
	width: 506px;
	padding: 12px 16px;
	margin: 0 0 0 43px;
}
/* 当进行editing过程时,整个div不显示,显示下面的input框 */
.todo-list li.editing .view {
	display: none;
}

.todo-list li .toggle {
	text-align: center;
	width: 40px;
	/* auto, since non-WebKit browsers doesn't support input styling */
	height: auto;
	position: absolute;
	top: 0;
	bottom: 0;
	margin: auto 0;
	border: 0; /* Mobile Safari */
	-webkit-appearance: none;
	appearance: none;
}

.toggle:before {
	background-image: url('./public/check-circle-regular.svg');
  	background-size: 100%;
	display: inline-block;
	margin-right: -7px;
	margin-top:12px;
	vertical-align: 3px;
	height: 16px;
	width: 16px;
	content: "";
}

.toggle:checked:before {
	background-image: url('./public/check-circle-solid.svg');
	background-size: 100%;
	display: inline-block;
	margin-right: -7px;
	margin-top:12px;
	vertical-align: -3px;
	height: 16px;
	width: 16px;
	content: "";
}



.todo-list li label {
	word-break: break-all;
	padding: 15px 60px 15px 15px;
	margin-left: 45px;
	display: block;
	line-height: 1.2;
	transition: color 0.4s;
}

.todo-list li.completed label {
	color: #d9d9d9;
	text-decoration: line-through;
}

.todo-list li .destroy {
	display: none;
	position: absolute;
	top: 0;
	right: 10px;
	bottom: 0;
	width: 40px;
	height: 40px;
	margin: auto 0;
	font-size: 30px;
	color: #cc9a9a;
	margin-bottom: 11px;
	transition: color 0.2s ease-out;
}

.todo-list li .destroy:hover {
	color: #af5b5e;
}

.todo-list li .destroy:after {
	content: '×';
}

.todo-list li:hover .destroy {
	display: block;
}

.todo-list li .edit {
	display: none;
}

.todo-list li.editing:last-child {
	margin-bottom: -1px;
}

.footer {
	color: #777;
	padding: 10px 15px;
	height: 20px;
	text-align: center;
	border-top: 1px solid #e6e6e6;
}

.footer:before {
	content: '';
	position: absolute;
	right: 0;
	bottom: 0;
	left: 0;
	height: 50px;
	overflow: hidden;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
	            0 8px 0 -3px #f6f6f6,
	            0 9px 1px -3px rgba(0, 0, 0, 0.2),
	            0 16px 0 -6px #f6f6f6,
	            0 17px 2px -6px rgba(0, 0, 0, 0.2);
}

.todo-count {
	float: left;
	text-align: left;
}

.todo-count strong {
	font-weight: 300;
}

.filters {
	margin: 0;
	padding: 0;
	list-style: none;
	position: absolute;
	right: 0;
	left: 0;
}

.filters li {
	display: inline;
}

.filters li a {
	color: inherit;
	margin: 3px;
	padding: 3px 7px;
	text-decoration: none;
	border: 1px solid transparent;
	border-radius: 3px;
}

.filters li a:hover {
	border-color: rgba(175, 47, 47, 0.1);
}

.filters li a.selected {
	border-color: rgba(175, 47, 47, 0.2);
}

.clear-completed,
html .clear-completed:active {
	float: right;
	position: relative;
	line-height: 20px;
	text-decoration: none;
	cursor: pointer;
}

.clear-completed:hover {
	text-decoration: underline;
}

.info {
	margin: 65px auto 0;
	color: #bfbfbf;
	font-size: 10px;
	text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
	text-align: center;
}

.info p {
	line-height: 1;
}

.info a {
	color: inherit;
	text-decoration: none;
	font-weight: 400;
}

.info a:hover {
	text-decoration: underline;
}


@media screen and (-webkit-min-device-pixel-ratio:0) {
	.toggle-all,
	.todo-list li .toggle {
		background: none;
	}

	.todo-list li .toggle {
		height: 40px;
	}

	.toggle-all {
		-webkit-transform: rotate(90deg);
		transform: rotate(90deg);
		-webkit-appearance: none;
		appearance: none;
	}
}

@media (max-width: 430px) {
	.footer {
		height: 50px;
	}

	.filters {
		bottom: 10px;
	}
}