思路如下:
通過Proxy代理uni相關方法,包裝爲Promise後返回
代碼如下:
/**
* 版本:1.0.0
* @author [email protected]
* 有問題和疑問可以發郵件聯繫~
*/
// 使用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)
}
}
}