<template>
  <div>
    <div v-for='data in dataList' :key='data.id' class='data-box' :class='{ 'new-data': data.newData }'>
      {{ data.name }}
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        dataList: []
      }
    },
    mounted() {
      this.getData()
      setInterval(() => {
        this.getData()
      }, 5000)
    },
    methods: {
      getData() {
        // 发送获取数据的请求
        axios.get('/api/data').then(res => {
          // 判断是否有新数据
          const newDatas = res.data.filter(item => !this.dataList.find(data => data.id === item.id))
          // 将新数据添加到列表头部
          newDatas.forEach(item => {
            item.newData = true
            this.dataList.unshift(item)
          })
          // 将原有数据更新
          res.data.forEach(item => {
            const index = this.dataList.findIndex(data => data.id === item.id)
            if (index !== -1) {
              this.$set(this.dataList, index, item)
            }
          })
        })
      }
    }
  }
</script>
<style>
  .new-data {
    animation: fade-in 1s ease-out;
  }
  @keyframes fade-in {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
</style>
Vue.js 定时拉取数据并淡入显示新内容 - 实用示例

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

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