(刷新數(shù)據(jù)不丟失)
<template>
<div id="app">
<input type="text" v-model="todo" v-on:keydown="addObj2($event)">
<button @click="addObj()">+添加</button>
<ul>
<h3>已完成</h3>
<li v-for="(item,key) in todoList" v-if="item.isdo"><input type="checkbox" v-model="item.isdo" @change="Change()">{{item.todo}} <button @click="deleteObj(key)">刪除</button></li>
</ul>
<ul>
<h3>未完成</h3>
<li v-for="(item,key) in todoList" v-if="!item.isdo" v-bind:class="{'Done':!item.isdo}"><input type="checkbox" v-model="item.isdo" @change="Change()">{{item.todo}} <button @click="deleteObj(key)">刪除</button></li>
</ul>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
data (){
return{
todo:'',
todoList:[],
isdo:true,
}
},
methods:{//用于放置自定義方法
addObj(){
if(!Object.is(this.todo,'')){
let obj={};
[obj.todo,obj.isdo]=[this.todo,this.isdo];
this.todoList.push(obj);
}
this.todo='';
localStorage.setItem('history',JSON.stringify(this.todoList));//將'this.list'以字符串的形式緩存在本地。
},addObj2(e){
if(e.keyCode===13){
let obj={};
[obj.todo,obj.isdo]=[this.todo,this.isdo];
this.todoList.push(obj);
this.todo='';
localStorage.setItem('history',JSON.stringify(this.todoList));
}
}
,deleteObj(key){
this.todoList.splice(key,1);//splice() 方法向/從數(shù)組中添加/刪除項(xiàng)目,然后返回被刪除的項(xiàng)目竖哩。
//arrayObject.splice(index,howmany,item1,.....,itemX):index 必需。整數(shù)脊僚,規(guī)定添加/刪除項(xiàng)目的位置相叁,使用負(fù)數(shù)可從數(shù)組結(jié)尾處規(guī)定位置。howmany 必需辽幌。要?jiǎng)h除的項(xiàng)目數(shù)量增淹。如果設(shè)置為 0,則不會刪除項(xiàng)目乌企。item1, ..., itemX 可選虑润。向數(shù)組添加的新項(xiàng)目。
localStorage.setItem('history',JSON.stringify(this.todoList));
},Change(){
localStorage.setItem('history',JSON.stringify(this.todoList));
}
},mounted(){//生命周期函數(shù)(這個(gè)是頁面刷新就會觸發(fā)的函數(shù))
let todoList = JSON.parse(localStorage.getItem('history'));//將緩存在本地的'history'字符串重新解析成對象加酵。
if(todoList){//如果'list'存在拳喻,執(zhí)行以下函數(shù)
this.todoList=todoList;
}
}
}
</script>
<style>
app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
.Done{
background: #ccc;
}
</style>