阿哇
阿哇
  • 发布:2019-07-08 21:04
  • 更新:2020-05-11 17:15
  • 阅读:3374

教你如何优雅的使用uni.xxxxx 异步接口

分类:uni-app

//配置 main.js  
//-------------------------main.js  
const $uni = new Proxy(uni, {//Proxy代理  
    get: (target, prop) => {  
        return (options) => {  
            return new Promise((resolve, reject) => {  
                target[prop]({  
                    success: resolve,  
                    fail: reject,  
                    ...options  
                })  
            })  
        }  
    },  
    set: (target, prop, value) => {  
        target[prop] = value  
    }  
})  
Vue.prototype.$uni = $uni // 挂载到vue上    可以直接this.$uni.xxxx()  

//如何使用  
//----------------------------.vue文件  
const userInfo= await this.$uni.getUserInfo()  
console.log(userInfo)  

const res=await  this.uni.getLocation({type: 'wgs84'})  
console.log('当前位置的经度:' + res.longitude);  
console.log('当前位置的纬度:' + res.latitude);  

//or  
try {  
const res=await  this.$uni.getLocation({type: 'wgs84'})  
console.log('当前位置的经度:' + res.longitude);  
console.log('当前位置的纬度:' + res.latitude);  
} catch (error) {  
    //todo    相当于 fail事件  
}  

//----------------.js文件  

import Vue from 'vue'  

const $uni= Vue.prototype.$uni  

const userInfo= await $uni.getLocation({type: 'wgs84'})  
console.log(userInfo)  

const res= await $uni.getLocation({type: 'wgs84'})  
console.log('当前位置的经度:' + res.longitude);  
console.log('当前位置的纬度:' + res.latitude);  
//or  
try {  
const res=await  $uni.getLocation({type: 'wgs84'})  
console.log('当前位置的经度:' + res.longitude);  
console.log('当前位置的纬度:' + res.latitude);  
} catch (error) {  
    //todo     相当于 fail事件  
}  

手动滑稽,有赞吗

3 关注 分享
SimpleJalon 8***@qq.com a***@qq.com

要回复文章请先登录注册

大话西游

大话西游

不错,不错。需要的时候可以这样用一下。挺好的。
2020-05-11 17:15
r***@21cn.com

r***@21cn.com

回复 2***@qq.com :
只能一个个函数写Promise?
2020-01-04 11:39
2***@qq.com

2***@qq.com

我这里报错。。 安卓 并不支持 Proxy
2019-08-11 12:27
风雅

风雅

赞一个 uniapp那么好的东西 但是社区真的不行
2019-07-08 22:58