<template>
  <view>
    <view v-for="(item, index) in dataList" :key="index">{{ item }}</view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      dataList: [], // 数据列表
      timer: null // 定时器
    }
  },
  onLoad() {
    this.getDataList() // 页面加载时先拉取一次数据
    this.timer = setInterval(() => {
      this.getDataList() // 每隔5秒拉取一次数据
    }, 5000)
  },
  methods: {
    getDataList() {
      // 从服务端拉取数据
      // 假设数据格式为 { data: ["数据1", "数据2", ...] }
      const res = await uni.request({
        url: 'xxxxx',
        method: 'GET'
      })
      const newDataList = res.data.data
      // 判断是否有新数据
      const hasNewData = newDataList.some(item => {
        return !this.dataList.includes(item)
      })
      if (hasNewData) {
        // 有新数据则淡入显示
        uni.showToast({
          title: '有新数据',
          icon: 'none',
          duration: 2000
        })
      }
      // 更新数据列表
      this.dataList = newDataList
    }
  },
  onUnload() {
    clearInterval(this.timer) // 页面卸载时清除定时器
  }
}
</script
用nvue帮我写一段每隔5秒从服务端定时拉取数据如果有新数据则在页面淡入显示

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

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