uni-app 异步化uni方法,支持await/async,适用所有方法

6,447 阅读1分钟

思路如下

通过Proxy代理uni相关方法,包装为Promise后返回

代码如下:

/**
 * 版本:1.0.0
 * @author i@tech.top
 * 有问题和疑问可以发邮件联系~
 */

// 使用proxy转换为异步化的uni方法
const uniAsync = new Proxy({}, {
	get(target, name) {
		return (obj) => new Promise((resolve, reject) => {
			uni[name]({
				...obj,
				success: ret => {
					resolve(ret)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
})

export default uniAsync

使用说明

在main.js中引用

// uni异步化
import uniAsync from '@/js_sdk/i-uni-async/uni-async.js'
// 设置到prototype
Vue.prototype.$uniAsync = uniAsync

使用方法,在页面或者组件中调用,支持所有uni方法!

// 以getImageInfo为例
export default {
	data() {
		return {}
	},
	methods: {
		async test() {
			const image = await this.$uniAsync.getImageInfo({
				src: ‘http://xxx.com/images/xxx.png’
			})
			console.log(image.path)
		}
	}
}

最后附上插件地址:ext.dcloud.net.cn/plugin?id=8…