如何让Vue支持本地存储?

这里我写一个最简单的例子,方便你扩展

存放目录

本地存储插件 localstorage.js 我放到了plugins下

组件搭建

创建存储关键字

const STORE_KEY = 'STORE-KEY';

创建初始化函数和存储方法

export default{
  data:null,
  install: function(Vue) {
    this.data = JSON.parse(window.localStorage.getItem(STORE_KEY)) || {};
    if(this.data==null){
      this.data = {};
    }
    Vue.prototype.$local = this;
    // this.clearItems();
  },
  save(){
    window.localStorage.setItem(STORE_KEY, JSON.stringify(this.data))
  },
}

启用

/**本地存储 */
import local from "./plugins/localstorage"
Vue.use(local);

使用

在任意当前模版下调用

this.$local.save()
  • 其他函数可自行扩展
  • 这里将对象进行json序列化,读取的时候从json中还原回去
  • 存储方法可以在router中写明,在切换页面时存储

你可能感兴趣的:(如何让Vue支持本地存储?)