1.模块化封装Storage实现缓存数据持久化
1.在src目录下新建目录model,在model目录下新建js文件取名storage.js
var storage={ set(key,value){ // 设置为本地缓存方法 localStorage.setItem(key,JSON.stringify(value)); }, get(key){ // 获取本地缓存方法 return JSON.parse(localStorage.getItem(key)); }, remove(key){ // 删除本地缓存方法 localStorage.removeItem(key); } } export default storage;
2.在App.vue中引用:
<template> <div id="app"> <!-- 监听键盘事件 --> <input type="text" v-model="todo" @keydown="AddText($event)"> <br> <hr> <h2>未完成</h2> <ul> <li v-for="(item,index) in list" :key="index"> <div v-if="!item.checkbox"> <input type="checkbox" v-model="item.checkbox" @change="saveList()"> {{item.title}}---<button @click="RemoveText(index)">删除</button> </div> </li> </ul> <h2>已完成</h2> <ul> <li v-for="(item,index) in list" :key="index" class="finish"> <div v-if="item.checkbox"> <input type="checkbox" v-model="item.checkbox" @change="saveList()"> {{item.title}}---<button @click="RemoveText(index)">删除</button> </div> </li> </ul> </div> </template> <script> // 引入模块 import storage from './model/storage.js'; export default { name: 'app', data () { return { todo:'', list:[], } }, methods:{ AddText(e){ if(e.keyCode==13){ this.list.push({title:this.todo,checkbox:false}) this.todo='' } // 设置为本地缓存 storage.set('list',this.list); }, RemoveText(key){ this.list.splice(key,1) storage.set('list',this.list); }, saveList(){ storage.set('list',this.list); } }, mounted(){ // 生命周期函数,vue页面刷新时触发 // 读取本地缓存 var list=storage.get('list'); if(list){ this.list=list } } } </script> <style> ul li{ list-style-type:none; } .finish{ background-color: #eee } </style>