客户端存储是对应用进行性能优化的绝佳方法,通过将数据存储在浏览器中,不必向服务器请求获取同一个信息,增强用户体验。在本文中,我们将介绍最简单的存储机制:Local Storage。Local Storage 使用键/值对来存储数据,它仅支持存储简单的值,但也可以通过 JSON 编解码来存储复杂的数据。
简单示例
在下面的示例中有 mounted 和 watch 两个方法,mounted 方法从 localStorage 中加载数据,watch 方法侦听 name 值的变化,并实时保存数据。
const app = new Vue({el: '#app',data: {name: ''},mounted() {if (localStorage.name) {this.name = localStorage.name;}},watch: {name(newName) {localStorage.name = newName;}}});
处理复杂的数据
为了存储对象和数组这样更复杂的数据,必须使用 JSON 来对数据进行序列化和反序列化。下面这个示例演示如何对数组进行持久化操作。
<div id="app"><h2>Cats</h2><div v-for="(cat, n) in cats"><span class="cat">{{ cat }}</span><button @click="removeCat(n)">Remove</button></div><div><input v-model="newCat"><button @click="addCat">Add Cat</button></div></div>
const app = new Vue({el: '#app',data: {cats: [],newCat: null},mounted() {if (localStorage.getItem('cats')) {try {this.cats = JSON.parse(localStorage.getItem('cats'));} catch(e) {localStorage.removeItem('cats');}}},methods: {addCat() {if (!this.newCat) {return;}this.cats.push(this.newCat);this.newCat = '';this.saveCats();},removeCat(x) {this.cats.splice(x, 1);this.saveCats();},saveCats() {const parsed = JSON.stringify(this.cats);localStorage.setItem('cats', parsed);}}})
