用nvue帮我写一段每隔5秒从服务端定时拉取数据如果有新数据则在页面scroll-view横向滚动中使用右移动画效果展示出来
<template>
<view>
<scroll-view class="scroll-view" :scroll-left="scrollLeft" scroll-x>
<view v-for="(item, index) in dataList" :key="index" class="item">{{ item }}</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
dataList: [], // 数据列表
timer: null, // 定时器
scrollLeft: 0 // 滚动距离
}
},
mounted() {
this.getData()
this.timer = setInterval(() => {
this.getData()
}, 5000)
},
methods: {
async getData() {
const res = await uni.request({
url: 'http://xxx.com/api/getData',
method: 'GET'
})
const newData = res.data // 新数据
if (newData.length > 0) {
// 有新数据,添加到数据列表中
this.dataList = [...this.dataList, ...newData]
const itemWidth = 120 // 每个元素宽度
this.scrollLeft = (this.dataList.length - 5) * itemWidth // 滚动距离
uni.createAnimation({
duration: 1000,
timingFunction: 'ease'
}).translateX(-itemWidth).step()
this.$nextTick(() => {
// 更新动画效果
this.$refs.scrollView.animation = animation.export()
})
}
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.scroll-view {
height: 100px;
white-space: nowrap;
}
.item {
display: inline-block;
width: 100px;
height: 80px;
margin-right: 10px;
background-color: #eee;
text-align: center;
line-height: 80px;
font-size: 28rpx;
}
</style
原文地址: https://www.cveoy.top/t/topic/hcUO 著作权归作者所有。请勿转载和采集!