vue中,每一秒一个data,如何保存所有data,并一次只要8条数据?

64 阅读1分钟

你可以通过在Vue组件中定义一个数组来保存所有的数据,然后在监听事件中实时截取需要显示的数据。可以借助Vue的生命周期钩子函数和计算属性来实现。

首先,在Vue组件的data中定义一个数组allData来保存所有的数据,并定义一个变量currentIndex来记录当前截取的位置:

data() {
  return {
    allData: [], // 保存所有数据
    currentIndex: 0, // 当前截取的位置
  }
},

然后,在监听事件的回调函数中,将返回的数据加入到allData数组中,并根据currentIndex截取需要显示的数据,同时更新currentIndex的值:

uni.$on('getData', (obj) => {
  let data = ['aa','bb','cc','dd','ee','ff'] // 假设返回的数据

  // 将返回的数据加入到allData数组中
  this.allData.push(...data)

  // 截取需要显示的数据
  let startIndex = this.currentIndex
  let endIndex = this.currentIndex + 8
  let result = this.allData.slice(startIndex, endIndex)

  // 更新currentIndex的值
  this.currentIndex += 8

  // 处理奇数偶数的情况,如果剩余的数据不足8条,则一起显示
  if (this.currentIndex >= this.allData.length) {
    this.currentIndex = 0
    result = this.allData.slice(startIndex)
  }

  console.log(result) // 打印需要显示的数据,根据需求进行操作
})

这样,每次监听到getData事件时,将返回的数据加入到allData数组中,根据currentIndex截取需要显示的数据。当currentIndex超过allData的长度时,重置currentIndex的值,并一起显示剩余的数据。

请根据实际需求在代码中进行适当的调整。