一 创建测试项目
vue init webpack-simple vuedemo
二 进入demo目录
cd vuedemo
三 安装依赖
cnpm install
四 修改代码App.vue
<template>
<div id="app">
<input type="text" v-model="todo" @keydown="doAdd($event)"/>
<h2>doing</h2>
<ul>
<li v-for="(item,key) in list" :key="item.id" v-if="!item.checked">
<input type="checkbox" v-model="item.checked" @change="saveList()"/> {{item.title}}--- <button @click="removeData(key)">Delete</button>
</li>
</ul>
<h2>done</h2>
<ul class ="finish">
<li v-for="(item,key) in list" :key="item.id" v-if="item.checked">
<input type="checkbox" v-model="item.checked" @change="saveList()"/> {{item.title}}--- <button @click="removeData(key)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "app",
data() {
return {
todo:'',
list:[
{
title:'write book',
checked:true
},
{
title:'lean cook',
checked:true
}
]
};
},
methods:{
doAdd(e){
if(e.keyCode == 13){//enter
this.list.push({title:this.todo, checked:false});
this.todo = ""
}
localStorage.setItem('list', JSON.stringify(this.list))
},
removeData(key){
this.list.splice(key, 1)
localStorage.setItem('list', JSON.stringify(this.list))
},
saveList(){
localStorage.setItem('list', JSON.stringify(this.list))
console.log("saveList" + this.list)
}
},
mounted: function () {//when vue refresh
var list = JSON.parse(localStorage.getItem('list'))
if(list){
this.list = list;
}
console.log("mounted" + list)
},
};
</script>
<style>
.finish li{
background:#eee;
}
</style>
五 运行
npm run dev
六 总结
1 了解vue的生命周期和生命周期钩子的函数
beforeCreate=>create
=>beforMount=>mounted
=>beforeUpdate=>updated
=>beforeDestroy=>destroyed
2 了解本地化存储
localStorage.setItem('list', JSON.stringify(this.list)) 写入本地存储
localStorage.getItem('list') 读取本地存储
3 了解JSON的格式化转换
JSON.stringify( ) 把json对象,转为字符串格式
JSON.parse() 把json字符串格式,转为json对象
七 参考
https://cn.vuejs.org/v2/guide/instance.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%BE%E7%A4%BA 生命周期图
https://cn.vuejs.org/v2/api/#mounted mounted钩子函数讲解
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage