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>