需求
给wx.setStorage等添加命名空间
- 根目录加 base_
- 子目录加 base_child_key、base_child2_key
- 如在child下存储 mobile=18888888888 则存储的结果为
key | val |
---|---|
base_child_mobile | 18888888888 |
版本1
- baseStorage.js
import {wx} from './wxapi';
const BASE = 'base_';
function setSync(key,data){
key = BASE + key;
return wx.setStorageSync(key,data);
}
function getSync(key){
key = BASE + key;
return wx.getStorageSync(key);
}
function removeSync(key){
key = BASE + key;
return wx.removeStorageSync(key);
}
export default {
setSync,
getSync,
removeSync
}
- childStorage.js
import base from '../utils/baseStorage';
const BASE = 'child_';
function setSync(key,data){
key = BASE + key;
return base.setSync(key,data);
}
function getSync(key){
key = BASE + key;
return base.getSync(key);
}
function removeSync(key){
key = BASE + key;
return base.removeSync(key);
}
export default {
setSync,
getSync,
removeSync
}
版本2
加入异步的几个方法,在wxapi已经promise化
- baseStorage.js
import {wx} from './wxapi';
const BASE = 'base_';
const storageFns = ['setStorage', 'getStorage', 'removeStorage', 'setStorageSync', 'getStorageSync', 'removeStorageSync'];
let newStorage = {};
storageFns.forEach(fnName => {
let newFn = function(key, ...data){
key = BASE + key;
return wx[fnName](key, ...data);
}
newStorage[fnName.replace('Storage', '')] = newFn;
})
export default newStorage
- childStorage.js
import base from '../utils/baseStorage';
const BASE = 'child_';
let storageNew = {};
for(let fnName in base){
let fnNew = function(key, ...args){
key = BASE + key;
return base[fnName](key, ...args);
}
storageNew[fnName] = fnNew;
}
export default storageNew
版本3
采用类继承的写法
- baseStorage.js
import {wx} from './wxapi';
/**
* 1. 添加命名空间
* 2. 简化方法名,去掉Storage
*/
const _storageFns = ['setStorage', 'getStorage', 'removeStorage', 'setStorageSync', 'getStorageSync', 'removeStorageSync'];
const _nameSpace = 'base_';
export class Storage {
nameSpace = _nameSpace;
constructor() {
_storageFns.forEach(fnName => {
let newFn = (key, ...data) =>{
key = this.nameSpace + key;
return wx[fnName](key, ...data);
}
this[fnName.replace('Storage', '')] = newFn;
})
}
}
- childStorage.js
import { Storage } from '../utils/baseStorage';
const _childSpace = 'child_';
class ChildStorage extends Storage {
constructor(){
super();
this.nameSpace = this.nameSpace + _ticketSpace;
}
}
export default new ChildStorage()
调用都是一样滴
版本1没有设置异步的 只有同步的可以用
import storage from '../common/ChildStorage';
storage.set('mobile', 18888888888)
.then(() => {
console.log('设置成功');
return storage.get('mobile');
})
.then(data => {
console.log(data);
})
网友评论