使用 Vue 的 Vant.js List 列表組件實現無限下拉


摘自:https://www.sunzhongwei.com/using-vue-vant-js-list-component-implementation-infinite-drop-down-list?from=sidebar_new

拉取歷史記錄,並在前端做無限下拉展示,是一個非常常見的使用場景。

最近在使用的 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;
                    }
                }
            });
        }
    }
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM