表格懒加载Demo(IntersectionObserver API 来检测某个特定元素是否进入视口)

34 阅读1分钟

表格懒加载Demo(IntersectionObserverAPI 来检测某个特定元素是否进入视口)

一、知识点

IntersectionObserver API 来检测某个特定元素是否进入视口,如果进入视口且当前没有正在加载,则触发方法来加载更多内容。

二、效果图

表格懒加载.jpg

三、实现代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.min.js"></script>

  <title>表格懒加载 Demo</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    th,
    td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }

    .loading {
      text-align: center;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div id="app">
    <h1>表格懒加载 Demo</h1>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>年龄</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
    <div v-if="loading" class="loading">Loading...</div>
    <div ref="loadMore" class="load-more"></div>
  </div>

  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          items: [],
          page: 1,
          pageSize: 10,
          loading: false,
          hasMore: true
        };
      },
      mounted() {
        this.loadItems();
        this.setupObserver();
      },
      methods: {
        async loadItems() {
          if (this.loading || !this.hasMore) return;
          this.loading = true;
          // 模拟异步请求数据
          const newItems = await this.fetchData(this.page);
          this.items = [...this.items, ...newItems];
          this.page++;
          this.loading = false;
          this.hasMore = newItems.length > 0;

          // 检查是否需要加载更多数据
          if (this.hasMore && this.setupObserver()) {
            this.loadItems();
          }
        },
        fetchData(page) {
          return new Promise(resolve => {
            setTimeout(() => {
              const data = [];
              const start = (page - 1) * this.pageSize + 1;
              const end = start + this.pageSize;
              for (let i = start; i < end; i++) {
                data.push({
                  id: i,
                  name: `User ${i}`,
                  age: Math.floor(Math.random() * 30) + 20
                });
              }
              resolve(data);
            }, 1000);
          });
        },
        setupObserver() {
          const observer = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting && !this.loading) {
              this.loadItems();
            }
          }, {
            rootMargin: '0px',
            threshold: 0.1
          });
          observer.observe(this.$refs.loadMore);
        }
      }
    });
  </script>
</body>

</html>