客户端存储是对应用进行性能优化的绝佳方法,通过将数据存储在浏览器中,不必向服务器请求获取同一个信息,增强用户体验。在本文中,我们将介绍最简单的存储机制:Local Storage。Local Storage 使用键/值对来存储数据,它仅支持存储简单的值,但也可以通过 JSON 编解码来存储复杂的数据。

简单示例

在下面的示例中有 mountedwatch 两个方法,mounted 方法从 localStorage 中加载数据,watch 方法侦听 name 值的变化,并实时保存数据。

  1. const app = new Vue({
  2. el: '#app',
  3. data: {
  4. name: ''
  5. },
  6. mounted() {
  7. if (localStorage.name) {
  8. this.name = localStorage.name;
  9. }
  10. },
  11. watch: {
  12. name(newName) {
  13. localStorage.name = newName;
  14. }
  15. }
  16. });

处理复杂的数据

为了存储对象和数组这样更复杂的数据,必须使用 JSON 来对数据进行序列化和反序列化。下面这个示例演示如何对数组进行持久化操作。

  1. <div id="app">
  2. <h2>Cats</h2>
  3. <div v-for="(cat, n) in cats">
  4. <span class="cat">{{ cat }}</span>
  5. <button @click="removeCat(n)">Remove</button>
  6. </div>
  7. <div>
  8. <input v-model="newCat">
  9. <button @click="addCat">Add Cat</button>
  10. </div>
  11. </div>
  1. const app = new Vue({
  2. el: '#app',
  3. data: {
  4. cats: [],
  5. newCat: null
  6. },
  7. mounted() {
  8. if (localStorage.getItem('cats')) {
  9. try {
  10. this.cats = JSON.parse(localStorage.getItem('cats'));
  11. } catch(e) {
  12. localStorage.removeItem('cats');
  13. }
  14. }
  15. },
  16. methods: {
  17. addCat() {
  18. if (!this.newCat) {
  19. return;
  20. }
  21. this.cats.push(this.newCat);
  22. this.newCat = '';
  23. this.saveCats();
  24. },
  25. removeCat(x) {
  26. this.cats.splice(x, 1);
  27. this.saveCats();
  28. },
  29. saveCats() {
  30. const parsed = JSON.stringify(this.cats);
  31. localStorage.setItem('cats', parsed);
  32. }
  33. }
  34. })