复杂业务场景解决方案
1. 支付集成
javascript
// 统一支付接口
export const pay = async (orderInfo) => {
#ifdef
MP - WEIXIN
return await weixinPay(orderInfo)
#endif
#ifdef
APP - PLUS
return await appPay(orderInfo)
#endif
#ifdef
H5
return await h5Pay(orderInfo)
#endif
}
// 微信小程序支付
async function weixinPay(orderInfo) {
return new Promise((resolve, reject) => {
uni.requestPayment({
provider: 'wxpay',
timeStamp: orderInfo.timeStamp,
nonceStr: orderInfo.nonceStr,
package: orderInfo.package,
signType: 'MD5',
paySign: orderInfo.paySign,
success: resolve,
fail: reject
})
})
}
2. 图片上传与预览
javascript
// 图片上传
export const uploadImage = (count = 1) => {
return new Promise((resolve, reject) => {
uni.chooseImage({
count,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePaths = res.tempFilePaths
const uploadTasks = tempFilePaths.map(path => {
return new Promise((resolve) => {
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: path,
name: 'file',
success: (uploadRes) => {
resolve(JSON.parse(uploadRes.data).url)
}
})
})
})
Promise.all(uploadTasks).then(resolve).catch(reject)
},
fail: reject
})
})
}
3. 长列表虚拟滚动
vue
<template>
<view class="virtual-list" :style="{ height: containerHeight }">
<view
class="list-container"
:style="{ transform: `translateY(${offsetTop}px)` }"
>
<view class="list-item" v-for="item in visibleItems" :key="item.id">
{{ item.content }}
</view>
</view>
</view>
</template>
<script>
export default {
props: {
items: {
type: Array,
default: () => []
},
itemHeight: {
type: Number,
default: 100
}
},
data() {
return {
containerHeight: '500px',
scrollTop: 0,
visibleCount: 0,
startIndex: 0
}
},
computed: {
visibleItems() {
return this.items.slice(this.startIndex, this.startIndex + this.visibleCount + 2)
},
offsetTop() {
return this.startIndex * this.itemHeight
}
},
mounted() {
// 计算可视区域能显示的条目数
const containerHeight = parseInt(this.containerHeight)
this.visibleCount = Math.ceil(containerHeight / this.itemHeight)
// 监听滚动事件
uni.createSelectorQuery()
.select('.virtual-list')
.onScroll((res) => {
this.scrollTop = res.scrollTop
this.startIndex = Math.floor(this.scrollTop / this.itemHeight)
})
.exec()
}
}
</script>