轻量级适用于 Vue2.0 的 localStorage 插件. (English Doc)
- 可根据组件名自动添加 namespace
- 对象存储友好化
- 获取存储值时可以使用类似 lodash/get 方法
- 可直接修改存储对象的单个属性
$ npm i vue-localstorage2 -S
在 Vue.js 中使用:
import localStorage2 from 'vue-localstorage2'
import Vue from 'vue'
Vue.use(localStorage2)
在其他框架中使用, 如 React:
import { Storage } from 'vue-localstorage2'
const storage = new Storage('app_name', 'app_prefix')
storage.set('item', 'value')
storage.get('item', 'default_value')
Vue.use(localStorage2, {
prefix: '<storage_prefix>', // default `app`
namespace: false // default `true`
})
通过类似 lodash/get 的方式获取存储在 storage 中的值.
this.$localStorage.get('name', 'tom')
this.$localStorage.get('list.0.name', 'tom')
get('list.0.name', 'tom')
其实相当于:
const _list = this.$localStorage.get('list')
get(_list, '0.name', 'tom')
this.$localStorage.set('name', 'tom')
this.$localStorage.set('list', [{ name: 'mary' }])
可直接修改对象的某一个键值, 但应该先保证获取对象 list.0
是否存在.
this.$localStorage.set('list.0.name', 'mary')
根据名称删除单个键值.
this.$localStorage.remove('name')
clear 方法并不会清除该域名下的所有 localStorage, 只会清除通过 vue-localstorage2 生成的值(即存储值的名称是以 prefix
+ component name
开始的键值对).
this.$localStorage.clear()
Copyright (c) 2017-present, Army-U. Released under the MIT License.