1.LocalStorage 是HTML5 本地存储
2.store.js
const STORAGE_KEY="todos-vuejs"
export default{
fetch:function(){
return JSON.parse(window.localStorage.getItem(STORAGE_KEY)||'[]')
},
save:function(items){
window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items))
}
}
3.App.vue中引入store.js
import Store from './store';
4.添加数组更改的监听事件,存入LocalStorage
watch:{
//监听数组更改
items:{
handler:function(items){
Store.save(items);//存储window.localStorage
},
deep:true //深层更改
}
}
5.页面初始化的值从LocalStorage中取出
items: Store.fetch()
6.完整代码
<template>
<div id="app">
<h1>{{title}}</h1>
<input v-model="newItem" @keyup.enter="addNew"/>
<ul>
<li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click="toggleFinish(item)">
{{item.label}}
</li>
</ul>
</div>
</template>
<script>
import Store from './store'; //调用store.js方法
export default {
data () {
return {
title: 'this is a todo list',
items: Store.fetch(), //存储记事的数组,从window.localStorage里取出存储的数据
newItem:'' //绑定input输入的值
}
},
methods:{
//点击记事完成的事件,isFinished取反,添加下划线
toggleFinish:function(item){
item.isFinished=!item.isFinished;
},
//新建记事
addNew:function(){
this.items.push({
label:this.newItem,
isFinished:false
});
this.newItem="";//清空重置,双向绑定
}
},
watch:{
//监听数组更改
items:{
handler:function(items){
Store.save(items);//存储window.localStorage
},
deep:true //深层更改
}
}
}
</script>
<style>
.finished{text-decoration:underline;}
</style>