Using asp.net as the back end and combining Vue.js with axios and vue-infinite-scroll to realize rolling loading

Keywords: Vue JSON axios Javascript

Rolling load, or infinite load, is a very popular way to display lists nowadays. When the content of a list is too long, it usually needs to be displayed in the form of pagination, but it seems very inhumane to always need users to click on the next page, so the technology of rolling loading comes out. As long as the content scrolls to the bottom, it automatically loads the content of the next page, and the user experience has just come out.

In this example, I use asp.net mvc. Firstly, I output JSON by paging data. Then I use Vue.js with axios to get data by AJAX method. Finally, I use vue-infinite-scroll to realize rolling loading.

Get paging data, in the controller, create a new Getlist,pageIndex represents the current page, pageSize is a page showing how many pieces of data, and finally total Count returns the total data of this list.

public List<Product> Getlist(int pageIndex, int pageSize, ref int totalCount)
        {
            var list=(from p in listall orderby p.ID descending select p).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            totalCount = listall.Count();

            return list.ToList();
        }

Next, we need to generate a JSON that has been paginated, record the total number of pages, and output it together:

 [HttpPost]
        public ActionResult ShowthePro(int? page)
        {
            int pageSize = 8;
            int pageIndex = page ?? 1;
            int totalCount = 0;

            var listpage = Getlist(pageIndex, pageSize, ref totalCount);
            int totalpage = (totalCount / pageSize) + 1;
            return Json(new {
                count=totalpage,
                data=listpage
            }, JsonRequestBehavior.AllowGet);
        }

At this point, let's use Vue.js and axios to test the non-automatic paging to see if there are any problems. Write js: first.

   Vue.prototype.$http = axios;
    new Vue({
        el: '#Pro',
        data: {
            peps: ''
        },
        mounted() {
            this.$http.post('/Json/ShowthePro?page=1').then(response=>this.peps = response.data.data);
        }
    })

Then the view template is made:

 <div class="row" id="Pro">
        <article class="work-item" v-for = "pep in peps">
            <a :href=pep.url class="icon fa-desktop" target="_blank"><img :src=pep.img alt="" />
              <h3>{{pep.name}}</h3></a>
        </article>

    </div>

Running successfully, then we need to use vue-infinite-scroll to achieve rolling load.

vue-infinite-scroll Github Home Page You can download it here and load it locally. Of course, you can also use CDN: https://unpkg.com/vue-infinite-scroll.

option

option Explain
infinite-scroll-disabled If the value of this property is true, infinite scrolling will be disabled.
infinite-scroll-distance Number(default = 0) When the distance between the bottom of the element and the bottom of the window reaches this value, execute v-infinite-scroll
infinite-scroll-immediate-check Boolean (default = true) indicates that the pseudo instruction should be checked immediately after binding. It is useful if the content is not high enough to fill a scrollable container.
infinite-scroll-listen-for-event When an event occurs in a Vue instance, infinite scrolling is checked again.

After understanding the basic application, we first load vue-infinite-scroll to our page

<script src="/Scripts/vue-infinite-scroll.js"></script>

Then modify the view code to add options to # Pro:

 <div class="row" id="Pro"  v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
   .......
   </div>

Finally, it is a key step to modify the js code. We have finished the back-end pagination and output it as JSON. Then we just need to let it scroll to load the paginated JSON automatically. When the number of pages reaches the total, we stop scrolling.

From the next example on the internet, we revised it according to this example.

<template>
    <div class="group-container" v-infinite-scroll="getActiveByAxios" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
    </div>
    <load-more tip="Loading" v-if="showLoading"></load-more>
</template>

  <script>
  import Vue from 'vue'
  import Axios from 'axios'
  import { LoadMore  } from 'vux'
  import infiniteScroll from 'vue-infinite-scroll'

  Vue.use(infiniteScroll);

 export default{
     data(){
         return {
          showLoading:true,
          busy: false,
          pageInfo:{
            count:0,
            pageIndex:1,
            pageSize:5
          },
         }
     },
     methods:{
         getActiveByAxios(){
                         if((that.pageInfo.pageIndex - 1) * that.pageInfo.pageSize >                     that.pageInfo.count){
                that.busy = false;
                that.showLoading = false;
                return;
              }
              Axios.get('url',{
                params:{
                  pageSize:that.pageInfo.pageSize,
                  pageNum:that.pageInfo.pageIndex
                }
              }).then(function (response) {
                if (response.data.success){
                  let list = response.data.data.commentList;
                  that.comments = that.comments.concat(list);
                  that.pageInfo.count = response.data.data.page.count;
                  that.pageInfo.pageIndex += 1;
                  setTimeout(() => {
                    that.busy = false;
                  }, 10);
                }
              }).catch(function (error) {

              })
         }
     }
 }

</script>

The first time I wrote it, something unexpected happened: I didn't use concat to connect the pages, which led to page-by-page flipping without adding up:

<script>
    Vue.prototype.$http = axios;
    var page = 1;

    new Vue({
        el: '#Pro',
        data: {
            pros: ''
        },
        busy: false,
        methods: {
            loadMore: function () {
                this.busy = true;

                setTimeout(() => {
                    this.$http.post('/Json/ShowthePro?page=' + page).then(response=>this.pros = response.data.data);
                        this.busy = false;

                    }, 1000);
                    page++;

                //End fro loadMore

            }
        }

    })
</script>

However, once concat is connected, JSON data will not be connected. After installing the Vue Dvetool plug-in in Chorme, I saw that the JSON data connected has errors. I think that the JSON initialized and the JSON data concat on the first page have errors. So long as the code confirms that the initialized JSON does not participate in concat, the code is quite simple.

 vm.$http.get('/Json/ShowthePro?page=' + pages).then(
                    function (response) {
                        var list1 = response.data.pros;
if (vm.pros.length == 0) {
                            this.pros = list1;
                        }
                        else {
                          var list2 = vm.pros;
                            vm.pros = list2.concat(list1);}  
                      pages++;
                        setTimeout(() => {
                            vm.busy = false;
                        }, 1000);
                    });

The test passed.

In order to prevent the current page from reading more data than all pages, I use a Boolean variable here. When the total number of pages exceeds, the entire infinite load stops running.

The complete code is as follows:

 Vue.prototype.$http = axios;
    var pages = 1;
    var totrue = true;
    new Vue({
        el: '#Pro',
        data: {
           pros:''
        },
        busy: false,
        methods: {
            loadMore: function () {
                this.busy = true;
                var vm = this;
                if (totrue){
                vm.$http.get('/Json/ShowthePro?page=' + pages).then(
                    function (response) {
                        var list1 = response.data.pros;
                        var count = response.data.count;
                        console.log(count);
                        if (vm.pros.length == 0) {
                            vm.pros = list1;
                        }
                        else {
                            if (pages <= parseInt(count)){
                            var list2 = vm.pros;
                            vm.pros = list2.concat(list1);

                            }
                            else {
                                totrue = false;
                            }
                        }
                        pages++;
                        setTimeout(() => {
                            vm.busy = false;
                        }, 1000);
                    });
                } else {

                }
                //End fro loadMore

            }
        }

    })

Every time you start a new framework or a new language, just like the men and women in first love, you try all kinds of harms before you have a definite relationship, and when you get it all started, all kinds of tenderness and sweetness will come to you. ~ uuuuuuu

Posted by sinisake on Tue, 01 Jan 2019 10:24:08 -0800