<template>
  <view>
    <scroll-view class="scroll-view" scroll-x>
      <view class="item" v-for="(item, index) in dataList" :key="index">{{ item }}</view>
    </scroll-view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      dataList: [] // 数据列表
    }
  },
  mounted() {
    this.getData() // 初始获取数据
    setInterval(() => {
      this.getData() // 每隔5秒获取数据
    }, 5000)
  },
  methods: {
    getData() {
      // 模拟从服务端获取数据
      const data = ['数据1', '数据2', '数据3', '数据4', '数据5']
      const newData = data.filter(item => !this.dataList.includes(item)) // 获取新数据
      if (newData.length > 0) {
        this.showNewData(newData) // 如果有新数据,展示出来
      }
    },
    showNewData(newData) {
      const len = this.dataList.length
      this.dataList = this.dataList.concat(newData) // 将新数据拼接到数据列表后面
      this.$nextTick(() => {
        // 获取scroll-view的宽度和item的宽度
        const scrollViewWidth = this.$refs.scrollView.$el.clientWidth
        const itemWidth = this.$refs.item[0].$el.offsetWidth
        // 计算需要移动的距离
        const moveDistance = itemWidth * newData.length
        // 创建动画
        const animation = uni.createAnimation({
          duration: 500,
          timingFunction: 'ease-out'
        })
        animation.translateX(-moveDistance).step()
        // 将动画应用到scroll-view上
        this.$refs.scrollView.$el.style.animation = animation.export()
        setTimeout(() => {
          // 动画结束后,清除动画样式并删除移动的item
          this.$refs.scrollView.$el.style.animation = ''
          this.dataList.splice(len, newData.length)
        }, 500)
      })
    }
  }
}
</script>
<style>
.scroll-view {
  white-space: nowrap;
  overflow: hidden;
}
.item {
  display: inline-block;
  width: 150px;
  height: 100px;
  margin-right: 10px;
  background-color: #ccc;
  text-align: center;
  line-height: 100px;
  font-size: 24px;
}
</style
用nvue帮我写一段每隔5秒从服务端定时拉取数据使用模拟数据如果有新数据则在页面scroll-view横向滚动中使用右移动画效果展示出来

原文地址: https://www.cveoy.top/t/topic/hcUV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录