使用 Vue 的 Vant.js List 列表组件实现无限下拉

文章目录

    拉取历史记录,并在前端做无限下拉展示,是一个非常常见的使用场景。

    最近在使用的 Vant (轻量、可靠的移动端 Vue 组件库),实现起来就非常方便。

    模板实现代码

    <div id="app" v-cloak>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="暂无更多数据"
          @load="load_more_items"
        >
            <van-cell
              v-for="item in items"
              :key="item"
              :title="item.name"
              :value="item.created_at"
              />
        </van-list>
    </div>
    

    Vue.js 实现代码

    new Vue({
        el: '#app',
    
        data: {
            items: [],
            finished: false,
            loading: false,
            offset: 0,
            page: 0,
            limit: 10,
        },
    
        mounted: function() {
            this.fetch_items();
        },
    
        methods: {
            load_more_items: function() {
                this.page += 1;
                this.offset = this.limit * this.page;
                this.fetch_items();
            },
    
            fetch_items: function() {
                var that = this;
    
                $.ajax({
                    url: `/api/get_items?offset=${this.offset}&limit=${this.limit}`,
                    type: 'get',
                    dataType: 'json',
                    success: function(data) {
                        that.loading = false;
                        if (data.data.length) {
                            that.items.push(...data.data);
                        } else {
                            that.finished = true;
                        }
                    }
                });
            }
        }
    });
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式