Vue 無限滾動元件

專注的小眼神發表於2018-12-11

infinite-scroll

前因

前段兒時間,公司內部做了個專案,原本的資料展示方式是table + pagination。本來感覺還不錯,but 使用者覺得分頁很不方便(沒法看到表格最後一行和第二頁第一行一塊顯示),後來想了想確實不方便。由此想到了滾動載入的方式。

後果

由於專案用的前端框架是Vue,所以就寫了一個基於vue簡單的滾動載入元件:CmInfiniteScroll

alt

使用方法

只需要用該元件把要實現滾動載入的區域包裹起來即可。

服務員~,上程式碼:

 <cm-infinite-scroll
      @scroll-to-bottom="onScrollToBottom">
      <ul>
        <li v-for="(news, index) in newsList" :key="index">
          <h2>{{news.title}}</h2>
          <p>{{news.content}}</p>
        </li>
      </ul>
    </cm-infinite-scroll>
    
<script>
    import CmInfiniteScroll from 'chaomeng-ui/CmInfiniteScroll'
    export default {
      name: 'infiniteScroll',
      components: {
        CmInfiniteScroll
      },
      data () {
        return {
          newsList: [
            { title: '新聞標題1', content: '內容1' },
            { title: '新聞標題2', content: '內容2' },
            { title: '新聞標題3', content: '內容3' },
            { title: '新聞標題4', content: '內容4' },
            { title: '新聞標題5', content: '內容5' }
          ]
        }
      },
      methods: {
        onScrollToBottom () {
          setTimeout(() => {
            this.newsList.push({
              title: `新聞標題${this.newsList.length + 1}`,
              content: `內容${this.newsList.length + 1}`
            })
          }, 1500)
        }
      }
    }
</script>
複製程式碼

當然還有更詳細的用法,可以參考專案中的示例,再次就不過多說了。

?坑

一開始專案中用到了ElementUIel-table作為內容的呈現方式,然後每次當我滾動到底部的時候,由於載入新資料的時候,滾動條不能自動向上滾動(el-table渲染新元素的方式導致),所以就會多次觸發scroll-to-bottom事件,後來加上threshold也不好使。無奈只好用了原生的table元素。

相關文章