之前使用vue开发的项目频繁使用到localStorage,封装了一下
localStorage.js文件代码如下:
let obj = {}; /**
* putLocalStorage 把数据放到本地存储
* @param {*} key
* @param {*} value
*/
obj.putLocalStorage = function (key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
}; /**
* getLocalStorage 获取本地存储数据
* @param {*} key
*/
obj.getLocalStorage = function (key) {
var obj = window.localStorage.getItem(key);
if (obj && obj != 'undefined' && obj != 'null') {
return JSON.parse(obj);
}
return '';
}; /**
* removeLocalStorage 清除本地数据
* @param {*} key
*/ obj.removeLocalStorage = function (key) {
if (key) {
window.localStorage.removeItem(key);
} else {
console.log(arguments)
for (var i in arguments) {
window.localStorage.removeItem(arguments[i]);
}
}
}; export default obj;
main.js中将其挂在到vue的原型属性上:
import localstorage from './assets/js/localstorage' Vue.prototype.$localstorage = localstorage
.vue文件中的使用方法:
存储:this.$localstorage.putLocalStorage('subMenu',this.subMenu) 获取:this.$localstorage.getLocalStorage('subMenu') 清除:this.$localstorage.removeItem('subMenu')