由于uni-app不完全支持proxy,所以需要自行实现一个proxy类,代理uni的接口,将success和fail的回调转为resolve和reject.
promisfy.js
/*
* @author: hruomei
* @description: uni-app接口promise化
* @create-time: 2020/05/19
* @last-update-time: 2020//05/19
* @version: V1.0
*/
let $uni;
// #ifdef MP
$uni = new Proxy(wx, {
get: (target, key) => {
return (options) => {
return new Promise((resolve, reject) => {
target[key]({
...options,
success: resolve,
fail: reject
});
})
}
},
set: (target, key, value) => {
target[key] = value;
}
})
// #endif
// #ifndef MP
$uni = new Proxy(uni, {
get: (target, key) => {
return (options) => {
return new Promise((resolve, reject) => {
target[key]({
...options,
success: resolve,
fail: reject
});
})
}
},
set: (target, key, value) => {
target[key] = value;
}
});
// #endif
export default $uni;
在main.js中
import $uni from './commons/promisfy.js'
Vue.prototype.$uni = $uni
使用方式
this.$uni.getSystemInfo().then(res => {}).catch(e =>{})
以上方案如果测试有效,后面的内容就不需要看了(本人使用HbuilderX2.6.0以上版本测试H5、APP、小程序三端有效)
存在的隐患
uni-app官方文档中说明,IOS8/IOS9/Android设备不支持Proxy(但是我测了是可以用),所以我们可以参考一下方案,模拟Proxy,实现代理
**这里只是一个小练习,H5端可以用,但在其他端uni对象被代理不能直接访问,所以在在H5端用着玩玩就好
promisfy.js
function isObject(target) {
return typeof(target) === 'object' || target === null;
}
function clone(target) {
if (!isObject(target)) return target;
let newTarget = new Object();
for (let i in target) {
newTarget[i] = clone(target[i]);
}
return newTarget;
}
// 因为uni的API只有一个层级,所以这里只代理了1个层级的API,UniProxy只针对uni-app
function UniProxy(target, handle) {
if (!isObject(target)) throw new Error('UniProxy(): variable "target" must be an object');
let targetCopy = clone(target);
Object.keys(targetCopy).forEach((key) => {
Object.defineProperty(targetCopy, key, {
get: () => {
return handle.get && handle.get(target, key);
},
set: (newVal) => {
handle.set && handle.set(target, key, newVal);
}
});
});
return targetCopy;
}
const $uni = new UniProxy(uni, {
get: (target, key) => {
return (options) => {
return new Promise((resolve, reject) => {
target[key]({
...options,
success: resolve,
fail: reject
});
})
}
},
set: (target, key, value) => {
target[key] = value;
}
});
export default $uni;
在main.js中
import $uni from './commons/promisfy.js'
Vue.prototype.$uni = $uni
使用方式
this.$uni.getSystemInfo().then(res => {}).catch(e =>{})