二、核心功能实现
1. 视频流组件优化
<template>
<view class="video-container">
<swiper
vertical
:current="currentIndex"
@change="onSwiperChange"
:style="{height: windowHeight + 'px'}"
>
<swiper-item
v-for="(item, index) in videoList"
:key="item.id"
>
<video
:src="item.url"
:autoplay="currentIndex === index"
:controls="false"
:loop="true"
:muted="muted"
@play="onVideoPlay(index)"
class="video-player"
></video>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
videoList: [],
windowHeight: 0,
muted: false
}
},
mounted() {
this.windowHeight = uni.getSystemInfoSync().windowHeight
this.loadVideos()
},
methods: {
async loadVideos() {
const res = await uni.request({
url: 'https://api.example.com/videos',
method: 'GET'
})
this.videoList = res.data
},
onSwiperChange(e) {
this.currentIndex = e.detail.current
}
}
}
</script>
2. 视频预加载策略
// 预加载相邻视频
preloadAdjacentVideos() {
const preloadCount = 2
const start = Math.max(0, this.currentIndex - preloadCount)
const end = Math.min(
this.videoList.length - 1,
this.currentIndex + preloadCount
)
for (let i = start; i <= end; i++) {
if (i !== this.currentIndex) {
const videoContext = uni.createVideoContext(
`video-${i}`, this
)
videoContext.seek(0).pause()
}
}
}
3. 社交互动功能
// 点赞动画实现
async likeVideo(videoId) {
try {
// 本地UI更新
this.videoList.forEach(item => {
if (item.id === videoId) {
item.isLiked = true
item.likesCount += 1
this.playLikeAnimation()
}
})
// 服务端同步
await uni.request({
url: '/api/like',
method: 'POST',
data: { videoId }
})
} catch (e) {
console.error('点赞失败', e)
}
},
playLikeAnimation() {
this.animation = uni.createAnimation({
duration: 1000,
timingFunction: 'ease-out'
})
this.animation.scale(1.2).opacity(0).step()
this.animation.scale(1).opacity(1).step({ duration: 0 })
this.animData = this.animation.export()
}
三、性能优化方案
1. 分页加载优化
// 滚动加载更多
onReachBottom() {
if (this.loading || !this.hasMore) return
this.loading = true
this.page += 1
uni.request({
url: '/api/videos',
data: { page: this.page },
success: (res) => {
this.videoList = [...this.videoList, ...res.data]
this.hasMore = res.data.length >= this.pageSize
},
complete: () => {
this.loading = false
}
})
}
2. 内存管理策略
// 清理不可见视频
cleanHiddenVideos() {
const visibleRange = 3 // 只保留前后3个视频
this.videoList.forEach((item, index) => {
if (Math.abs(index - this.currentIndex) > visibleRange) {
const videoContext = uni.createVideoContext(
`video-${index}`, this
)
videoContext.stop() // 释放资源
}
})
}
四、多端适配技巧
- 条件编译:处理平台差异
- 像素级适配:使用upx/rpx单位
- API兼容:封装统一接口
- 组件扩展:开发平台专属组件
发布数据对比
开发周期:原生方案1/3时间
代码复用率:85%+
性能差异:<15%
包体大小:小程序2MB/App15MB