Home  >  Article  >  Web Front-end  >  How to build infinite scroll and waterfall flow layout using Vue?

How to build infinite scroll and waterfall flow layout using Vue?

WBOY
WBOYOriginal
2023-06-27 13:32:301867browse

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>{{item.title}}</h3>
      <p>{{item.desc}}</p>
      <img :src="item.imgUrl" :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>{{item.title}}</h3>
      <p>{{item.desc}}</p>
      <img :src="item.imgUrl" :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