案例介紹
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()
}
}
}
}