案例介绍
TodoList是作为新手入门的最好训练案例,在该案例中包含了很多Vue的知识点,例如:
条件渲染、列表渲染指令
表单数据绑定
事件处理和事件修饰符
计算属性
生命周期钩子函数
localStorage本地存储
自定义指令
除了上面的知识点外,最重要的就是熟悉Vue的开发流程。所以,多练习一下TodoList案例对新手来说是最好的入门案例了,下面给大家分享一下源码和演示效果。
案例要求
使用 vue + localStorage 完成案例;
输入任务,按回车添加任务;
双击编辑任务;
编辑完成按回车保存,按Esc撤销编辑;
点击复选框表示已经完成任务;
点击X删除任务;
html代码
<template>
<div>
<strong>TODOLIST:</strong>
<input type="text" v-model="inputValue" @keydown.enter="submit">
<h3>进行中({{noLength}})</h3>
<ul>
<li v-for="(item,index) in todoList" :key="index" v-show="!item.done">
<input type="checkbox" @click.prevent="change(item,true)">
<span v-if="index!=updateIndex" @dblclick="update(item,index)">{{item.title}}</span>
<input v-if="index==updateIndex"
type="text"
v-model="item.title"
@keydown.enter="updateSave"
@keydown.esc="backData(item)"
@blur="updateSave"
v-focus
>
<span class="del-btn" @click="del(index)">×</span>
</li>
</ul>
<h3>已完成({{yesLength}})</h3>
<ul>
<li v-for="(item,index) in todoList" :key="index" v-show="item.done">
<input type="checkbox" checked @click.prevent="change(item,false)">
<span v-if="index!=updateIndex" @dblclick="update(item,index)">{{item.title}}</span>
<input v-if="index==updateIndex"
type="text"
v-model="item.title"
@keydown.enter="updateSave"
@keydown.esc="backData(item)"
@blur="updateSave"
v-focus
>
<span class="del-btn" @click="del(index)">×</span>
</li>
</ul>
</div>
</template>
<style scoped>
.del-btn{
margin-left:20px;
font-size:16px;
color:red;
cursor:pointer;
}
ul{
list-style: none;
padding: 0;
margin: 0;
}
ul li{
line-height: 30px;
}
</style>
JS代码
export default {
data(){
return {
inputValue: "", // 输入框的值
todoList: [], // 数据
updateIndex: -1, //要修改的元素下标
tempValue: "" //临时保存信息的变量
}
},
created(){
// 初始化数据
let todoList = localStorage.todoList;
if(todoList){
this.todoList = JSON.parse(todoList)
}
},
computed:{
noLength(){ // 计算未完成的元素长度
let count = 0
this.todoList.map(item=>{
if(!item.done){
count++
}
})
return count
},
yesLength(){ // 计算已完成的元素长度
let count = 0
this.todoList.map(item=>{
if(item.done){
count++
}
})
return count
}
},
methods:{
submit(){
// 提交
this.todoList.push({
title: this.inputValue,
done: false
})
// 置空输入框
this.inputValue = ""
//同步
this.save();
},
change(item,checked){
// 点击复选框,改变完成状态
if(checked){
item.done = true
}else{
item.done = false
}
this.save();
},
update(item,index){
// 把元素的内容临时保存到一个变量中
this.tempValue = item.title
// 设置要修改元素的下标
this.updateIndex = index
},
updateSave(){
// 修改后保存
this.save()
// 还原数据
this.updateIndex = -1
this.tempValue = ""
},
backData(item){
// 按esc键还原,设置当前元素的内容为保存的临时变量值
item.title = this.tempValue
// 清除要修改的元素下标
this.updateIndex = -1
// 清除临时变量
this.tempValue = ""
},
del(index){
// 根据下标删除元素
this.todoList.splice(index,1)
this.save()
},
save(){
//同步数据
localStorage.todoList = JSON.stringify(this.todoList)
}
},
directives: { // 自定义指令
focus: {
inserted(el){
el.focus()
}
}
}
}