Vue.js Client-Side Storage;( Web Storage/localStorage)

原文:https://cn.vuejs.org/v2/cookbook/client-side-storage.html

LocalStorage (api)

my code pen :https://codepen.io/chentianwei411/pen/oagZNM

最简单的存储机制。

LocalStorage使用key/value。不能存储复杂数据格式。

因此只使用小的存储。如用户设置,form data.

大的数据和复杂的存储需要用的如  .IndexedDB,

可以使用插件: vue-local-storage  (353✨) 用的人很少

my code pen :https://codepen.io/chentianwei411/pen/wYBdOj

如果储存复杂数据, 如object, array。需要使用JSON格式存储数据,serialize and deserialize the values with JSON。

  • 从localStorage.getItem("cats")的数据,需要JSON.parse()转化成javascript格式
  • 向localStorage.setItem("cats", parsedData), 需要使用JSON.stringify()转化成JSON格式
  mounted: function() {
    if (localStorage.getItem('cats')) {
      try {
        this.cats = JSON.parse(localStorage.getItem('cats'));
      } catch(e) {
        localStorage.removeItem("cats");
      }
    }
  },
  methods: {
    addCat: function() {
      if ( this.newCat == '' || this.newCat == null ) {
        return
      }
      this.cats.push(this.newCat);
      this.newCat = '';
      this.saveCats();
    },
    saveCats: function() {
      const parsed = JSON.stringify(this.cats);
      localStorage.setItem('cats', parsed);
    },
    removeCat: function(n) {
      this.cats.splice(n, 1);
      this.saveCats();
      console.log(this.cats)
    }
  }
原文地址:https://www.cnblogs.com/chentianwei/p/9711797.html