为了优雅的coding,今天把微信自带的Storage封装了一下
在util文件夹里新建Storage.js
class Storage {
constructor(namespace) {
// 命名空间:防止污染全局
this.namespace = namespace
}
set(key, value) {
// 这一步是将当前的命名空间里的数据都存到localStorage里
// 微信中获取的数据就是对象
let storage = wx.getStorageSync(this.namespace)
if (!storage){
// 没有数据默认空对象
storage = {}
}
storage[key] = value
// 将数据更新到localStorage
// 微信自动做了处理,不用转string了
wx.setStorageSync(this.namespace, storage)
}
get(key,def) {
let storage = wx.getStorageSync(this.namespace)
// 获取不到数据就返回默认值
if(!storage) return def
return storage[key]
}
}
// 导出
module.exports = {
Storage
}
使用记录:
我是在globalData里挂载上去的,随便怎么用都可以
// app.js
const {Storage} = require("./utils/storage")
App({
// ...
globalData: {
userInfo: new Storage("userInfo")
}
})
// pages/personal/personal.js
// 从全局里获取Storage的实例化对象
const userInfoStorage = getApp().globalData.userInfo
Page({
data: {
avatarImg:""
},
// ...
click(){
wx.getUserProfile({
desc: '完善用户信息',
success: res => {
const data = JSON.parse(res.rawData)
const token = res.encryptedData
const nickName = data.nickName
const avatarImg = data.avatarUrl
userInfoStorage.set("token",token)
userInfoStorage.set("nickName",nickName)
userInfoStorage.set("avatarImg",avatarImg)
this.setData({avatarImg:data.avatarUrl})
}
})
},
})
Storage里的数据是这样的,很优雅,elegant!
userInfo:{
"token":"LnrYTlA0AWLqzUyxvWHfoJOjV2Vh0Pinxil/IljUula4ghA6Ugvm6Xwe5A7cGaiO3C+qpQZhQwWXwAcO6GY9yvMVzkU7QZ+XLsGadtlzm+Ztp0W2rrc/LCQzoYv0b9wxVyACTKVfIatzLypr+RyazO9FiW8JVxCNMs0GYRL6HE3Ks9qgjXyZEx4434GmVXH133QhSJ7bE7FEdLjGAaiqgrZM3s7/+J4tFknf1Bl0dZcyo7d6qPoA56JS3xEGtuQVj9uxnFmuNOxNOkedUFEsGGd91YFq87QQA8v+ptKAB8RoVg4BVRFOJwMXZKQcVw0P9qg9ZzPy9TmW79nVSOjpZpTJWf0yqSq9H4odvNB793XHTI0zQhvmaXzljzfwQl6kUjMMPGc+Jpn0indEQiUYhQ==",
"nickName":"阿辉",
"avatarImg":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTI0XCRPe79gy9QZPQpbic9YEls1dheyDD93zQhpZqOom39Hg9lbibLtxGJAg8YEo8aXsviaZ0E9gIDOg/132"
}