search
HomeWeb Front-endJS Tutorialvue-infinite-loading2.0 usage instructions

This time I will bring you the instructions for using vue-infinite-loading2.0, what are the precautions when using vue-infinite-loading2.0, the following is a practical case, let's take a look.

Introduction

This is an infinite scroll plug-in used in Vue.js, which can help you quickly create an infinite scroll list.

Features

  1. Mobile friendly support

  2. Compatible with any scrollable element

  3. There are different rotators that can be used as loading animations

  4. Supports displaying results after loading

  5. Supports two Unlimited loading in all directions

Installation

Note : vue-infinite-loading2.0 can only be used in Vue.js2.0. If you want to use it in Vue.js1.0, please install vue-infinite-loading1.3 version

npm install vue-infinite-loading --save

Import method

es6 module import method

import InfiniteLoading from 'vue-infinite-loading';
export default {
 components: {
  InfiniteLoading,
 },
};

CommonJS module import method

const InfiniteLoading = require('vue-infinite-loading');
export default {
 components: {
   InfiniteLoading,
 },
};

Other methods

<script></script>

vue-infinite-loading.js will be registered A global variable VueInfiniteLoading needs to be used like this:

 ...
 components: {
   VueInfiniteLoading:VueInfiniteLoading.default,
 }
...

Start

Basic use

In this example, we To create a basic infinite list, there are three steps:

  1. In your template, use v-for to create a list

  2. Place the InfiniteLoading component at the bottom of the list;

  3. Set the ref attribute of the InfiniteLoading component to infiniteLoading because it is used to trigger events.

  4. Create and bind a loading callback function to the InfiniteLoading component.

##Template

<template>
 <p>
  </p>
<p>
  Line:
  <span></span>
  </p>
  <infinite-loading>  </infinite-loading>
 
</template>

Script

import InfiniteLoading from 'vue-infinite-loading';
export default {
 data() {
  return {
   list: []
  };
 },
 methods: {
  onInfinite() {
   setTimeout(() => {
    const temp = [];
    for (let i = this.list.length + 1; i on<strong>onInfinite</strong> In the function, each time we push 20 numbers into the list array. We use <strong>setTimeout</strong> to simulate asynchronous requests. Finally, don't forget to trigger an <strong>$InfiniteLoading:loaded</strong> event, which will tell the <strong>InfiniteLoading</strong> component that the data has been downloaded successfully. <p style="text-align: left;"></p>Now, we can show the effect based on the above code. <p style="text-align: left;"></p><p style="text-align: left;"></p><p id="hacker">Example: Hacker News List Page</p><strong></strong>In this example, we will imitate a Hacker News List page, but will use <strong>InfiniteLoading</strong> instead of <strong>pagination</strong><p style="text-align: left;"></p>Before starting this example, we need to prepare the following:<p style="text-align: left;"></p> <ol class=" list-paddingleft-2">
<li>Get the news list API, in this case we use HN Search API<p style="text-align: left;"></p>
</li>
<li>Import axios plug-in to request data<p style="text-align: left;"></p>
</li>
</ol><p style="text-align: left;">Template<strong></strong></p><pre class="brush:php;toolbar:false"><p>
 </p><p>
  <a>
   ![](https://news.ycombinator.com/y18.gif)
  </a>
  <span>Hacker News</span>
</p>
<p>
 <span></span>
 </p><p>
  <a></a>
 </p>
 <p>
  <small>
   <span></span>
   points by
   <a></a>
    |
   <a></a>
  </small>
 </p>

 <infinite-loading>
 <span>
  There is no more Hacker News :(
 </span>
 </infinite-loading>
In the template, we created a header and a list for the Hacker News list. The InfiniteLoading component in this example is used somewhat differently from the previous example. We customized the prompt content when there is no more data based on slot.

Script

import InfiniteLoading from 'vue-infinite-loading';
import axios from 'axios';
const api = 'http://hn.algolia.com/api/v1/search_by_date?tags=story';
export default {
 data() {
  return {
   list: []
  };
 },
 methods: {
  onInfinite() {
   axios.get(api, {
    params: {
     page: this.list.length / 20 + 1
    }
   }).then((res) => {
    if (res.data.hits.length) {
     this.list = this.list.concat(res.data.hits);
     this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
     if (this.list.length / 20 === 3) {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
     }
    } else {
     this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
    }
   });
  }
 },
 components: {
  InfiniteLoading
 }
};
In the onInfinite function, we request a page of news and push them into the list each time in the array. If we request 3 pages of news, the $InfiniteLoading:complete event will be triggered to tell the InfiniteLoading component that there is no more data to load. It will display the prompt content we customized in the template to indicate that there is no more data.

Style

.hacker-news-list .hacker-news-item {
  margin: 10px 0;
  padding: 0 10px 0 32px;
  line-height: 16px;
  font-size: 14px;
}
.hacker-news-list .hacker-news-item .num {
 margin-top: 1px;
 margin-left: -32px;
 float: left;
 width: 32px;
 color: #888;
 text-align: right;
}
.hacker-news-list .hacker-news-item p {
 padding-left: 8px;
 margin: 0;
}
.hacker-news-list .hacker-news-item .num:after {
 content: ".";
}
.hacker-news-list .hacker-news-item p>a {
 color: #333;
 padding-right: 5px;
}
.hacker-news-list .hacker-news-item p a {
 text-decoration: none;
}
.hacker-news-list .hacker-news-item p small, .hacker-news-list .hacker-news-item p small a {
 color: #888;
}

Use with filter

在上个例子的基础上,我们将在头部创建一个下拉选择作为过滤器,当我们改变过滤器,列表将会重新加载。

Template

<p>
</p><p>
 <a>
  ![](https://news.ycombinator.com/y18.gif)
 </a>
 <span>Hacker News</span>
 <select>
  <option>Story</option>
  <option>Poll</option>
  <option>Show hn</option>
  <option>Ask hn</option>
  <option>Front page</option>
 </select>
</p>
<p>
 <span></span>
 </p><p>
  <a></a>
 </p>
 <p>
  <small>
   <span></span>
   points by
   <a></a>
   |
   <a></a>
  </small>
 </p>

<infinite-loading>
 <span>
  There is no more Hacker News :(
 </span>
</infinite-loading>

Script

import InfiniteLoading from 'vue-infinite-loading';
import axios from 'axios';
const api = 'http://hn.algolia.com/api/v1/search_by_date';
export default {
 data() {
  return {
   list: [],
   tag: 'story'
  };
 },
 methods: {
  onInfinite() {
   axios.get(api, {
    params: {
     tags: this.tag,
     page: this.list.length / 20 + 1
    }
   }).then((res) => {
    if (res.data.hits.length) {
     this.list = this.list.concat(res.data.hits);
     this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
     if (this.list.length / 20 === 10) {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
     }
    } else {
     this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
    }
   });
  },
  changeFilter() {
   this.list = [];
   this.$nextTick(() => {
    this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
   });
  }
 },
 components: {
  InfiniteLoading
 }
};

changeFilter函数中,我们清楚了列表并等待DOM更新,然后我们触发一个$InfiniteLoading:reset事件,目的是让 InfiniteLoading 组件回到最初状态,它将立刻请求新的数据。

Style

在上个例子基础上增加样式

.demo-inner {
 margin-left: 20px;
 width: 261px;
 height: 455px;
 border: 1px solid #ccc;
 overflow: auto;
}
.hacker-news-list .hacker-news-header {
  padding: 2px;
  line-height: 14px;
  background-color: #f60;
}
.hacker-news-list {
 min-height: 455px;
 background-color: #f6f6ef;
}
.hacker-news-list .hacker-news-header select {
  float: right;
  color: #fff;
  background-color: transparent;
  border: 1px solid #fff;
  outline: none;
}

服务端渲染

服务端渲染(SSR)是Vue.js2.0的新特性,当你在你的SSR应用中使用这个组件,会得到类似这样的错误:

Error: window is not defined
ReferenceError: window is not defined
  at ...
  at ...
  at e.exports (...)
  at Object. (...)
  at p (...)
  at Object.e.exports.render.e (...)
  at p (...)
  at Object. (...)
  at p (...)
  at e.esModule.default (...)

因为style-loader不支持在这个时候本地导出,详情点这里,所以我们需要下面的变通方案,为了你的SSR应用:

import InfiniteLoading from 'vue-infinite-loading/src/components/Infiniteloading.vue';

代替

 import InfiniteLoading from 'vue-infinite-loading';

npm install less less-loader --save-dev 如果你还没有安装它们。

然后你的SSR应用应该运行良好。如果不是,你可以加入这个issue去讨论。

属性

on-infinite

这是一个回调函数,当滚动到距离滚动父元素底部特定距离的时候,会被调用。

通常,在数据加载完成后,你应该在这个函数中发送$InfiniteLoading:loaded事件。

- type      Function
- reuqired    true

distance

这是滚动的临界值。如果到滚动父元素的底部距离小于这个值,那么on-infinite回调函数就会被调用。

- type     Number
- required   false
- default   100
- unit     pixel

spinner

通过这个属性,你可以选择一个你最喜爱旋转器作为加载动画。点击这里可以看到所有可用的旋转器。

- type     String
- required   false
- default   'default'

ref

正如你所知,这个属性是一个Vue.js的官方指令,用来获取子组件的实例。我们需要用它来得到 InfiniteLoading 组件的实例来发送事件。你可以用这种方式来得到实例:this.$refs[the value of ref attribute].

- type   String
- required   true

direction

如果你设置这个属性为top,那么这个组件将在你滚到顶部的时候,调用on-infinite函数。

警告:你必须在数据加载后,手动地将滚动父元素的scrollTop设置为正确的值,否则,该组件会一次又一次调用on-infinite函数。

- type     String
- default   'bottom'

事件

InfiniteLoading 组件将处理一下事件。如果你需要通过组件的实例来$emit,则可以通过ref属性来得到组件实例。

$InfiniteLoading:loaded

通常,你需要在数据加载后发送这个事件, InfiniteLoading组件将隐藏加载动画,并且准备下一次触发。

$InfiniteLoading:complete

如果InfiniteLoading组件就不会接收$InfiniteLoading:loaded,当你发送这个事件后,它将为用户显示一个没有结果的提示。如果InfiniteLoading组件接收过$InfiniteLoading:loaded,当你发送这个事件的时候,它会为用户显示一个没有更多内容的提示。你可以利用slot来自定义需要显示的内容。

你的onInfinite函数可能像这个样子:

onInfinite() {
  this.$http.get(url, (res) => {
  if (res.data) {
   this.list = this.list.concat(res.data);
   this.$refs[your ref attirbute's value].$emit('$InfiniteLoading:loaded');
  } else {
   this.$refs[your ref attirbute's value].$emit('$InfiniteLoading:complete');
  }
 });
}

$InfiniteLoading:reset

InfiniteLoading组件将会回到最初的状态,并且on-infinite函数将会立刻被调用。大部分情况下,如果你把这个组件同过滤器或制表符一起使用,这个事件还是有用的。

插槽

你可以利用slot自定义提示的内容,当然,如果你喜欢的话,也可以使用默认内容:

 <span>
  {{ Your content }}
 </span>

no-results

InfiniteLoading组件接收到$InfiniteLoading:complete 事件并且它没有接收过$InfiniteLoading:loaded事件时,这个内容会显示出来。

- type    String
- default   No results :(

no-more

InfiniteLoading组件接收到$InfiniteLoading:complete 事件并且它已经接收过$InfiniteLoading:loaded事件时,这个内容会出现。

spinner

如果,你不喜欢当前旋转器,你可以自定义自己的旋转器作为加载时的动画。

- type     HTML
- default   default spinner

旋转器

你可以用spinner属性,选择你最喜爱的旋转器作为加载动画:

<infinite-loading></infinite-loading>

点击这里可以查看几个可用的旋转器。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue组件与复用使用详解

Vue无限加载vue-infinite-loading使用详解

The above is the detailed content of vue-infinite-loading2.0 usage instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.