Vue scroll down to load more data scroll case detailed explanation

Vue scroll down to load more data scroll case detailed explanation

vue-infinite-scroll

Install

npm install vue-infinite-scroll --save

Although the official also recommends several loading methods, the "most vue" way is definitely to add it in main.js

import infiniteScroll from 'vue-infinite-scroll'
Vue.use(infiniteScroll)

Implementation Example

The official code examples assume that you write code in the root component. In fact, we must write code in the child component, so the code also needs to be slightly modified. Only useful code snippets are listed below:

<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
    <div v-for="item in data" :key="item.index">{{item.name}}</div>
</div>
 data () {
    return {
      count: 0,
      data: [],
      busy: false
    }
  }
methods: {
    loadMore: function() {
      this.busy = true
      setTimeout(() => {
        for (var i = 0, j = 10; i < j; i++) {
          this.data.push({name: this.count++ })
        }
        console.log(this.data)
        this.busy = false
      }, 1000)
    }
  }

Effect

By default, 10 rows of data will be loaded. As long as you scroll down to the bottom of the page, 10 more items will be loaded after 1 second. Then, if you continue to scroll, another 10 items will be loaded. As shown below:

Option Explanation

  • v-infinite-scroll="loadMore" means the callback function is loadMore
  • infinite-scroll-disabled="busy" means that the variable busy determines whether loadMore is executed. If false , loadMore is executed, and if true , it is not executed. Please note that busy means busy, and it is not executed when busy.
  • infinite-scroll-distance="10" Here 10 determines how many pixels away from the end of the page the page scrolls to before triggering the callback function. 10 is the pixel value. Usually we will make a "Loading..." several dozen pixels high at the end of the page. In this case, we can set the height of this div to the value of infinite-scroll-distance .

Other options:

  • infinite-scroll-immediate-check The default value is true . This directive means that the value of busy and whether it has scrolled to the bottom should be checked immediately after binding. If your initial content height is not high enough to fill the scrollable container, you should set it to true , which will immediately execute a loadMore , which will help you fill in some initial content.
  • infinite infinite-scroll-listen-for-event will check again.
  • infinite-scroll-throttle-delay checks the value of busy for a certain time interval. The default value is 200. This is because the basic principle of vue-infinite-scroll is that vue-infinite-scroll will cyclically check the value of busy and whether it has scrolled to the bottom. The callback function will only be executed if busy is false and the scroll has reached the bottom.

Practical Application

As you can see, the example above is constantly modifying the data variable, and the data in the data variable is constantly increasing, which seems to be correct. However, in practice, our new data must be obtained by Ajax, not by using a for loop to inject useless natural numbers as in the example. Moreover, setTimeout is not needed. What we want is to execute Ajax immediately when the page scrolls to the bottom. In fact, the setTimeout in the above code is just to simulate a delayed loading effect, not to say that Ajax must be delayed for 1 second.

What to do in actual combat?

You just need to change this simulated Ajax code to the real Ajax code for getting data:

 setTimeout(() => {
        for (var i = 0, j = 10; i < j; i++) {
          this.data.push({name: this.count++ })
        }
        console.log(this.data)
        this.busy = false
      }, 1000)

In addition, this.busy = false must also be used as the Ajax callback


vue-scroller

Install

npm install vue-scroller -d

Use in main.js

import VueScroller from 'vue-scroller'
Vue.use(VueScroller)

use

Note: It is best to set a high

<scroller style="top: 100px;" :height='400' :on-refresh="refresh" :on-infinite="infinite" ref="myscroller">
     <div class="order-box" v-for="(item,index) in orderList" :key="index">
                
     </div>
 </scroller>

data

data(){
           return {
                status:'all',
                orderList:[],
                page:0,
                all_page:1,
            }
        },

Pull down to refresh

refresh (done) {
                setTimeout(()=>{
                    done();
                },1500)
            },

Pull up to load more

  • Note: If done is called before the data is assigned to the template, the drop-down function will be triggered all the time, so we need to call it after the template is assigned in the callback of the successful request.
  • The drop-down function is bound to the scroller tag by binding attributes, so we don't need to call the request function once in create. When the page is initialized, the drop-down function will be automatically called once to obtain the data of the first page.
//Pull down to trigger infinite (done) {
                if(this.page>=this.all_page){
                    setTimeout(()=>{
                        this.$refs.myscroller.finishInfinite(true);
                    },1500)
                }else{
                    
                    setTimeout(()=>{
                        this.page++;
                        this.getorderList(done)
                        
                    },500);
                }
            },
 
getorderList(done){
                this.$http({
                    method:'post',
                    url:'/seckill/server/orderList',
                    data:{
                        jwt:this.jwt,
                        status:this.status,
                        page:this.page,
                        page_size:5
                    }
                }).then(res=>{
                    if(res.data.code == 0){
                        
                        
                        this.orderList.push.apply(this.orderList,res.data.data.list)
                        this.$refs.myscroller.finishInfinite(true)
 
                        this.page = res.data.data.page
                        this.all_page = res.data.data.all_page
                        done();
                    }else{
                       
                    }
                })
            },

Notice

If it involves switching the tab bar, you need to reset the state of the scroller. When the finishInfinite(false) parameter is false, the pull-up function will be called again to reset the current state of the scroller.

goodsAll(){
                this.status = 'all'
                this.page = 0
                this.all_page = 1
                this.$refs.myscroller.finishInfinite(false);
                this.orderList = []
            },

triggerPullToRefresh() triggers pull-down refresh

finishPullToRefresh() Complete pull-to-refresh

this.$refs.my_scroller.finishInfinite(false)
finishInfinite(isNoMoreData :Boolean) When the parameter is false, the pull-up data acquisition can be called again. When the parameter is true, the pull-up data callback function stops being used, and the lower part of the pull-down no longer displays loading, but displays "No more data"


vue-infinite-loading

Install

npm install vue-infinite-loading --save

Use within component

// Component class uses import InfiniteLoading from 'vue-infinite-loading';
 
export default {
  components: { InfiniteLoading }
}
 
//Use the basic version <infinite-loading
  spinner="spiral"
  @infinite="infiniteHandler"
  :distance="200"
  class="infinite-loading-wrap"
>
  <!-- <div slot="spinner">Loading...</div> -->
  <div slot="no-more">No more Data</div>
  <div slot="no-results">No results Data</div>
  <!-- <div slot="error" slot-scope="{ trigger }">
	Error Data, click <a href="javascript:;" rel="external nofollow" rel="external nofollow" @click="trigger">here</a> to retry
  </div> -->
</infinite-loading>

Basic Usage

<template>
  <div> 
		    <p v-for="(item,index) in list" :key="index"> 
			     <span v-text="item"></span> 
		    </p> 
		    <!--The infinite-loading component should be placed at the bottom of the list, inside the scrolling box! -->
		<infinite-loading
			spinner="spiral"
			@infinite="infiniteHandler"
			:identifier="infiniteId"
			:distance="200"
			class="infinite-loading-wrap"
		>
			<div slot="spinner">Loading...</div>
			<div slot="no-more">No more Data</div>
			<div slot="no-results">No results Data</div>
			<div slot="error" slot-scope="{ trigger }">
			  Error Data, click <a href="javascript:;" rel="external nofollow" rel="external nofollow" @click="trigger">here</a> to retry
			</div>
		</infinite-loading> 
	 </div>
</template>
 
<script> 
 import InfiniteLoading from 'vue-infinite-loading';
  export default {
    data() {
      return {
		  infiniteId: +new Date(), // reset scroll state change page: 1,
        list: []
      };
    },
    methods: {
		// Reset scroll state rest(){
		  this.list = [];
		  this.page = 1;
		  this.infiniteId += 1;
		},
      async infiniteHandler($state) {
			// Simulate request data const res = await this.$axios.workList({ page: this.page, pagesize: 20 });
			  if (res.data.list.length) {
				this.page += 1;
				this.list = this.list.concat(res.data.list);
				$state.loaded();
			  } else {
				$state.complete();
			  }
        // Here simulates a loading delay of 1 second //setTimeout(() => {
         // let temp = [];
         // for (let i = this.list.length + 1; i <= this.list.length + 20; i++) {
          // temp.push(i);
         // }
         // this.list = this.list.concat(temp);
         // $state.loaded();
        //}, 1000);
      //},
    },
    components: { InfiniteLoading }
  }
</script>

Paging Usage

<template>
  <div>
    <ul>
      <li class="hacker-news-item" v-for="(item, key) in list"></li>
    </ul>
    <infinite-loading @infinite="infiniteHandler">
      No more Data
    </infinite-loading>
  </div>
</template>    
 
<script>
import InfiniteLoading from "vue-infinite-loading";
import axios from "axios";
export default {
  data() {
    return {
      list: [],
    };
  },
  methods: {
    infiniteHandler($state) {
      let api = "http://xxx.com/xxx"; // api requests data address for you axios
        .get(api, {
          params: {
            // Page number parameters (10 per page)
            page: this.list.length / 10 + 1,
          },
        })
        .then((response) => {
          if (response.data.length) {
            // response.data is the array list returned by your request interface this.list = this.list.concat(response.data);
            $state.loaded();
            if (this.list.length / 10 === 10) {
              // Here 10 pages of data are loaded, and the setting is not to load anymore $state.complete();
            }
          } else {
            $state.complete();
          }
        });
    },
  },
  components: { InfiniteLoading },
};
</script>

Description: $state: This component will pass a special event parameter $state to the event handler to change the loading state. The $state parameter includes three methods, namely loaded method, complete method and reset method.

  • The loaded method is used to stop the animation after each data load, and then the component will be ready for the next trigger.
  • The complete method is used to complete the infinite loading, and the component will no longer process any scrolling operations. If the method is never called when loaded calls the complete method, this component will display the result message for the user, if not, it will display no more user messages, and other content can be set by slot
  • The reset method returns the component to its original state

Conditional usage

<template>
    <div class="hacker-news-list">
          <div class="hacker-news-header">
            <!--Pull down to change-->
            <select v-model="tag" @change="changeFilter()">
                  <option value="story">Story</option>
                  <option value="history">History</option>
            </select>
              <!--Or click to change-->
            <button @click="changeFilter()">Search</button>
          </div>
          <ul>
              <li class="hacker-news-item" v-for="(item, key) in list"></li>
           </ul>
           <!--Don't forget to set this ref="infiniteLoading"-->
          <infinite-loading @infinite="infiniteHandler" ref="infiniteLoading">
            No more data
          </infinite-loading>
    </div>
</template>
 
<script>
    import InfiniteLoading from 'vue-infinite-loading';
    import axios from 'axios';
 
    export default {
          data() {
            return {
                  list: [],
                  tag: 'story',
            };
          },
          methods: {
            infiniteHandler($state) {
                  const api="http://xxx.com/xxx";
                  //api requests data address for you axios.get(api, {   
                    params: {
                        // Changed conditional parameters tags: this.tag,  
                          page: this.list.length / 10 + 1,
                    },
                  }).then(({ data }) => {
                    if (data.result.length) {
                          this.list = this.list.concat(data.result);
                          $state.loaded();
                          if (this.list.length / 20 === 10) {
                            state.complete();
                          }
                    } else {
                          $state.complete();
                    }
                  });
            },
            //Change the conditional bar using this method changeFilter() {
                  this.list = [];
                  this.$nextTick(() => {
                    this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
                  });
            },
          },
          components: { InfiniteLoading }
    }
</script>

Stabilization

import { debounce } from "lodash"; // Anti-shake // Anti-shake get: debounce(async function () {
  let k = await this.$axios.getList_API();
  console.log(k, "Anti-shake version");
}, 1000),

This is the end of this article about Vue scrolling down to load more data - scroll - case. For more relevant Vue loading data content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue implements an example of pulling down and scrolling to load data
  • Vue example of using mouse scroll to load data
  • Sample code for infinite loading of data when scrolling to the bottom of the page under Vue
  • Detailed explanation of two ways to load data using Vue.Js combined with Jquery Ajax
  • Javascript vue.js table paging, ajax asynchronous loading of data
  • Vue.js table paging ajax asynchronous loading of data

<<:  MySQL 8.0.18 installation tutorial under Windows (illustration)

>>:  Docker deployment of Flask application implementation steps

Recommend

How to connect a Linux virtual machine to WiFi

In life, the Internet is everywhere. We can play ...

MySQL 8.0.15 installation graphic tutorial and database basics

MySQL software installation and database basics a...

A brief analysis of the use of watchEffect in Vue3

Preface Everyone should be familiar with the watc...

js to achieve simple magnifying glass effects

This article example shares the specific code of ...

Causes and solutions for slow MySQL query speed and poor performance

1. What affects database query speed? 1.1 Four fa...

The difference and usage of LocalStorage and SessionStorage in vue

Table of contents What is LocalStorage What is Se...

Vue implements small form validation function

This article example shares the specific code of ...

CentOS7 uses yum to install mysql 8.0.12

This article shares the detailed steps of install...

MySQL 5.6 root password modification tutorial

1. After installing MySQL 5.6, it cannot be enabl...

Detailed explanation of replace into example in mysql

Detailed explanation of replace into example in m...

CSS3 analysis of the steps for making Douyin LOGO

"Tik Tok" is also very popular and is s...

How to create WeChat games with CocosCreator

Table of contents 1. Download WeChat developer to...