search
HomeWeb Front-endVue.jsHow to build infinite scroll and waterfall flow layout using Vue?

Vue.js is a popular JavaScript framework that allows developers to easily create dynamic, responsive web applications. Among them, it is especially favored by developers for its powerful component development capabilities. Infinite scrolling and waterfall layout have become one of the indispensable features in modern web development.

This article aims to introduce how to use Vue.js, combined with some third-party libraries, to achieve infinite scrolling and waterfall flow layout functions.

Achieving Infinite Scroll

Infinite Scroll refers to continuing to load more content when scrolling to the bottom of the page to achieve infinite expansion of page content. This technique works for thousands of data entries and can greatly improve the user experience.

Data source preparation

First we need to prepare a data source, which contains at least some data items. Here we use a simple example to illustrate. Suppose we have an infinitely scrollable list containing 100 data items. The data source can be like this:

[
  {id: 1, text: 'Item 1'},
  {id: 2, text: 'Item 2'},
  // ... more data
  {id: 99, text: 'Item 99'},
  {id: 100, text: 'Item 100'},
]

Install and use the vue-infinite-scroll library

Next, we need to install a library called vue-infinite-scroll, which provides the core mechanism of the infinite scroll function, as well as the necessary instructions and components. To install this library, you can use the npm command:

npm install vue-infinite-scroll

Globally register the required instructions:

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

In our component, we need to set some configuration and data:

<template>
  <div class="scroll-list" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
    <ul>
      <li v-for="(item, index) in items" :key="index">{{ item.text }}</li>
    </ul>
    <div v-if="busy" class="loading">
      Loading ...
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      items: [], // 当前列表所有数据
      busy: false, // 标记是否正在请求数据
      page: 1, // 当前数据分页
      perPage: 10, // 每页数量
      total: 100, // 总数据量
    }
  },
  methods: {
    loadMore() {
      // 标记正在加载数据
      this.busy = true
      // 模拟请求延迟
      setTimeout(() => {
        // 构造新数据
        const newItems = []
        const from = (this.page - 1) * this.perPage + 1
        const to = this.page * this.perPage
        for (let i = from; i <= to && i <= this.total; i++) {
          newItems.push({
            id: i,
            text: 'Item ' + i
          })
        }
        // 加载新数据
        this.items = [...this.items, ...newItems]
        // 增加当前页数
        this.page++
        // 去除加载数据标记
        this.busy = false
      }, 1000)
    }
  }
}
</script>

Code Description

  • v-infinite-scroll="loadMore": Used to specify the callback function to load more data
  • infinite-scroll -disabled="busy": Used to specify whether data is currently being requested
  • infinite-scroll-distance="10": Used to specify how many pixels the scroll bar is from the bottom Trigger loading data behavior

Implement waterfall flow layout

Waterfall flow (Waterfall) is a common layout. Its core concept is: items of different sizes can appear in the same row , the waterfall flow layout automatically adjusts with the number of projects. We can use a Vue third-party component library called vue-waterfall to easily implement waterfall layout with just a few lines of code.

Install and use the vue-waterfall library

First, we need to install the vue-waterfall component library:

npm install vue-waterfall

Global registration component:

import waterfall from 'vue-waterfall'
Vue.use(waterfall)

Then we You can use the waterfall flow layout in the component:

<template>
  <waterfall>
    <div v-for="(item, index) in items" :key="index">
      <h3 id="item-title">{{item.title}}</h3>
      <p>{{item.desc}}</p>
      <img src="/static/imghwm/default1.png"  data-src="item.imgUrl"  class="lazy"  : :alt="item.title">
    </div>
  </waterfall>
</template>
<script>
import axios from 'axios'

export default {
  data () {
    return {
      items: []
    }
  },
  created () {
    axios.get('https://api.example.com/items').then(response => {
      this.items = response.data
    })
  }
}
</script>

Code description

This code uses the axios library to obtain data from a data source. The structure of the data is roughly as follows:

[
  {
    title: 'Item 1',
    desc: 'This is item 1',
    imgUrl: 'https://example.com/item1.png',
  },
  {
    title: 'Item 2',
    desc: 'This is item 2',
    imgUrl: 'https://example.com/item2.png',
  },
  // ...
]

Optimize infinite scrolling and waterfall flow layout

In fact, in real application scenarios, you will face a common problem when dealing with infinite scrolling and waterfall flow layout: when the data source is very large, the component Performance will drop dramatically, causing responses to become sluggish or even laggy. Here we introduce some optimization strategies to improve component performance.

Using virtual scrolling technology

The basic idea of ​​virtual scrolling technology is to render only the data seen by the user according to the view interval, rather than rendering all the data. In this way we can greatly reduce the rendering cost of the component, thus improving performance. The vue-virtual-scroll-list component is a reliable library for implementing virtual scrolling, which can be used in conjunction with the vue-infinite-scroll or vue-waterfall libraries.

Install vue-virtual-scroll-list library:

npm install vue-virtual-scroll-list

When using this library, you need to make the following modifications in the component:

<template>
  <virtual-scroll-list :size="75" :remain="10" :items="items" :key-field="'id'">
    <div slot-scope="{item}">
      <h3 id="item-title">{{item.title}}</h3>
      <p>{{item.desc}}</p>
      <img src="/static/imghwm/default1.png"  data-src="item.imgUrl"  class="lazy"  : :alt="item.title">
    </div>
  </virtual-scroll-list>
</template>
<script>
import axios from 'axios'
import VirtualScrollList from 'vue-virtual-scroll-list'

export default {
  components: { VirtualScrollList },
  data () {
    return {
      items: []
    }
  },
  created () {
    axios.get('https://api.example.com/items').then(response => {
      this.items = response.data
    })
  }
}
</script>

Among them, we pass vue- The waterfall component is replaced with the vue-virtual-scroll-list component to achieve the virtual scrolling effect.

Parted loading

Another way to reduce the pressure of component rendering is to load data in parts. This method is similar to the infinite scroll mentioned earlier, but when loading data, instead of pulling all the data at once, it loads segmented data on demand. How to implement segmented loading? A simple solution is to load only the first N pieces of data at a time, and then load the next piece of data after the user scrolls to the bottom. This method is suitable for situations where the amount of data is relatively large.

<template>
  <div class="scroll-list" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
    <ul>
      <li v-for="(item, index) in items" :key="index">{{ item.text }}</li>
    </ul>
    <div v-if="busy" class="loading">
      Loading ...
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      items: [], // 当前列表所有数据
      busy: false, // 标记是否正在请求数据
      page: 1, // 当前数据分页
      perPage: 10, // 每页数量
      total: 100, // 总数据量
    }
  },
  methods: {
    loadMore() {
      // 标记正在加载数据
      this.busy = true
      // 模拟请求延迟
      setTimeout(() => {
        // 构造新数据
        const newItems = []
        const from = (this.page - 1) * this.perPage + 1
        const to = this.page * this.perPage
        for (let i = from; i <= to && i <= this.total; i++) {
          newItems.push({
            id: i,
            text: 'Item ' + i
          })
        }
        // 加载新数据
        if (this.page <= 10) {
          this.items = [...this.items, ...newItems]
          // 增加当前页数
          this.page++
        } else {
          this.busy = true
        }
        // 去除加载数据标记
        this.busy = false
      }, 1000)
    }
  }
}
</script>

In this code, we have modified the loadMore function. It will now only pull the first 10 pages of data. In this way, even if there is a lot of data, the burden on the component can be reduced by gradually loading.

Summary

In this article, we introduced how to use Vue.js to create infinite scroll and waterfall flow layout functions, and also implemented some optimization measures to improve the performance of components. Generally speaking, the three libraries vue-infinite-scroll, vue-waterfall and vue-virtual-scroll-list are enough to complete our work, but in actual development, we also need to consider various scenarios and different data structures. , to choose the solution that best suits your current project.

The above is the detailed content of How to build infinite scroll and waterfall flow layout using Vue?. 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
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft