在写个list的小demo时,经常会遇到下面这个问题
当刷新后,下面的list就都不见了。因此可以用localStorage。localStorage就是用来本地存储数据的。先看下完整的代码:
vue文件:
<template>
<div id="app">
<h2 v-text="title"></h2>
<input type="text" v-model="newItem" v-on:keyup.enter="addNew"/>
<ul>
<li v-for="item in items" v-on:click="toggleFinish(item)" v-bind:class="{finished:item.isFinished}">{{item.label}}</li>
</ul>
</div>
</template>
<script>
import Store from './store.js'
console.log(Store)
export default {
data:function(){
return{
items:Store.fetch(),
title:"to do a list",
newItem:''
}
},
watch:{
items:{
handler:function(items){
Store.save(items)
},
deep:true//深复制
}
},
methods:{
toggleFinish:function(item){
item.isFinished=!item.isFinished
},
addNew:function(){
this.items.push({
label:this.newItem,
isFinished:false
})
this.newItem=''
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.finished{
text-decoration:underline;
}
</style>
store.js文件
const STORAGE_KEY='todos-vuejs'
export default{
fetch(){
return JSON.parse(window.localStorage.getItem(STORAGE_KEY)||'[]')
},
save(items){
window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items))
}
}
结果:
具体关键点如下:
1、通常新输入的数据要先保存在本地,然后刷新时,要从本地读取新数据,所以store.js文件中一个fecth读取数据函数,一个save保存数据函数。
2、store.js写好后,要引入该js文件
3、用watch来监听输入数据的变化,有变化时就调用save函数保存变化
其中deep:true是深复制,就是不仅是数据,连其状态什么的都一块复制了,如例子中的isFinished就复制了
4、到这里只是保存了新添加的数据在本地,但是还需要读取出来
调用fetch函数就可以吧新数据读取出来。