How to implement simple vue infinite loading instructions
This article mainly introduces the method of implementing simple vue infinite loading instructions. It has certain reference value. Now I share it with you. Friends in need can refer to the custom instructions in
vue. It operates on the underlying DOM. Let's introduce how to customize a simple instruction by scrolling to the bottom to load data and achieving infinite loading.
The principle of infinite loading is to monitor the scrolling event. Each time you scroll, you must obtain the scrolled distance. If the scrolling distance plus the browser window height is greater than or equal to the content height, the function will be triggered. Download Data.
First introduce how to achieve infinite loading without using vue.
Do not use frames
The first is html:
<!DOCTYPE html><html lang="en"> <head><meta charset="UTF-8"> <title>实现滚动加载</title> <style> * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } li, ul { list-style: none; } .container { width: 980px; margin: 0 auto; } .news__item { height: 80px; margin-bottom: 20px; border: 1px solid #eee; }</style> </head> <body> <p class="container"> <ul class="news" id="news"> <li class="news__item">1、hello world</li> <li class="news__item">2、hello world</li> <li class="news__item">3、hello world</li> <li class="news__item">4、hello world</li> <li class="news__item">5、hello world</li> <li class="news__item">6、hello world</li> <li class="news__item">7、hello world</li> <li class="news__item">8、hello world</li> <li class="news__item">9、hello world</li> <li class="news__item">10、hello world</li> </ul> </p> </body> </html>
Open the browser and adjust the browser window Height to make the page scrollable.
First understand the three variables
document.body.scrollTop The distance the scroll bar scrolls
window. innerHeight browser window height
document.body.clientHeight content height
corresponds to the above principle is
window.addEventListener('scroll', function() { var scrollTop = document.body.scrollTop; if(scrollTop + window.innerHeight >= document.body.clientHeight) { // 触发加载数据 loadMore(); } }); function loadMore() { console.log('加载数据')' }
loadMore() function is to get the data from the interface, assemble the html, and insert it behind the original node.
// 表示列表的序号 var index = 10; function loadMore() { var content = ''; for(var i=0; i< 10; i++) { content += '<li class="news__item">'+(++index)+'、hello world</li>' } var node = document.getElementById('news'); // 向节点内插入新生成的数据 var oldContent = node.innerHTML; node.innerHTML = oldContent+content; }
This achieves infinite loading.
Use instructions to implement in vue
Why do we need to use instructions to implement it? It seems that only instructions can get the underlying DOM? To achieve infinite loading, you need to obtain the content height.
First initialize a project and add a component to display the list.
// components/Index.vue <template> <p> <ul class="news"> <li class="news__item" v-for="(news, index) in newslist"> {{index}}-{{news.title}} </li> </ul> </p> </template> <style> .news__item { height: 80px; border: 1px solid #ccc; margin-bottom: 20px; } </style> <script> export default{ data(){ return{ newslist: [ {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'}, {title: 'hello world'} ] } } } </script>
OK, now start writing instructions. From the traditional implementation, we learned that we need to register to listen for scroll events and get the content height at the same time.
directives: { scroll: { bind: function (el, binding){ window.addEventListener('scroll', ()=> { if(document.body.scrollTop + window.innerHeight >= el.clientHeight) { console.log('load data'); } }) } } }
First, the scroll instruction is registered in the component, and then when the instruction is bound to the component for the first time, that is, corresponding to the bind hook, the scroll is registered monitor.
Hook functions are functions that are called when some life cycles change. bind is called when it is bound to the component for the first time, and unbind is called when the instruction is unbound from the component.
You can also notice that bind corresponds to two parameters of the function, el and binding. These are hook function parameters. For example, el corresponds to the bound node. Binding has a lot of data, such as the ones passed to the instructions. Parameters etc.
The el.clientHeight below represents the content height of the node that obtains the binding instruction.
As before, determine whether the scroll height plus the window height is greater than the content height.
Bind the command to the node:
<template> <p v-scroll="loadMore"> <ul class="news"> <li class="news__item" v-for="(news, index) in newslist"> {{index}}-{{news.title}} </li> </ul> </p> </template>
You can see that a value is passed to the command, which is the function to load data:
methods: { loadMore() { let newAry = []; for(let i = 0; i < 10; i++) { newAry.push({title: 'hello world'}) } this.newslist = [...this.newslist, ...newAry]; } }
Of course, now when scrolling to the bottom, only load data will be printed. Just change this to call a function and it will be OK:
window.addEventListener('scroll', ()=> { if(document.body.scrollTop + window.innerHeight >= el.clientHeight) { let fnc = binding.value; fnc(); } })
The loadMore of v-scroll="loadMore" can be obtained from the binding of the hook function parameter.
At this point, a simple command is completed.
Optimization
The above example does not actually obtain data from the interface, so there is a hidden bug: when the interface response is very slow, scroll to the end When the data is being loaded, a slight scrolling will still trigger the data acquisition function, which will cause multiple interface requests at the same time and return a large amount of data at once.
The solution is to add a global variable scrollDisable. When the loading data function is triggered for the first time, set the value to true, and use this value to determine whether to execute the loading function.
Take ordinary implementation as an example:
var scrollDisable = false; window.addEventListener('scroll', function() { var scrollTop = document.body.scrollTop; if(scrollTop + window.innerHeight >= document.body.clientHeight) { // 触发加载数据 if(!scrollDisable) { // loadMore(); } } }); // 表示列表的序号 var index = 10; function loadMore() { // 开始加载数据,就不能再次触发这个函数了 scrollDisable = true; var content = ''; for(var i=0; i< 10; i++) { content += '<li class="news__item">'+(++index)+'、hello world</li>' } var node = document.getElementById('news'); // 向节点内插入新生成的数据 var oldContent = node.innerHTML; node.innerHTML = oldContent+content; // 插入数据完成后 scrollDisable = false; }
The above is the entire content of this article. I hope it will be helpful to everyone’s learning. More related Please pay attention to the PHP Chinese website for content!
Related recommendations:
About the configuration introduction of using Typescript in Vue2 Vue-cli
##About the implementation of the Vue comment framework (Implementation of parent component)
The above is the detailed content of How to implement simple vue infinite loading instructions. For more information, please follow other related articles on the PHP Chinese website!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
