Home Web Front-end Vue.js How to implement scrolling loading of images or lists in Vue?

How to implement scrolling loading of images or lists in Vue?

Jun 25, 2023 pm 03:40 PM
vue rolling loading Picture list

As web applications become more and more complex, we often need to display a large number of pictures or lists on the page. If you load all the content at once, it will greatly affect the page loading speed and user experience. In this case, scrolling loading has become a very popular method.

Rolling loading, also called infinite scrolling, refers to the process of requesting subsequent data in real time through AJAX technology when the user scrolls the page. This technology is widely used in social media sites like Facebook, Twitter, Instagram, etc. to achieve an efficient experience.

In Vue.js, there are usually two ways to implement rolling loading. One is to write code yourself, and the other is to use a third-party plug-in. Next, we will introduce them one by one.

1. Write your own code to implement rolling loading

Vue.js provides a very convenient instruction v-scroll, which can be used to monitor the scrolling events of the page. We can determine whether the scrollTop distance of the div element reaches the bottom when scrolling. If it reaches the bottom, subsequent data requests will be triggered.

The following is a sample code that uses v-scroll to implement scrolling loading of images:

<template>
  <div class="image-list" v-scroll="onScroll">
    <div class="image" v-for="image in images" :key="image.id">
      <img :src="image.src" />
    </div>
    <div v-if="loading">加载中...</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      images: [],
      loading: false,
      page: 1,
      pageSize: 10
    }
  },

  mounted() {
    this.loadImages()
  },

  methods: {
    loadImages() {
      this.loading = true
      // 模拟请求数据,每次请求 10 条数据
      setTimeout(() => {
        let start = (this.page - 1) * this.pageSize
        let end = start + this.pageSize
        for (let i = start; i < end; i++) {
          this.images.push({
            id: i,
            src: `http://www.example.com/images/${i}.jpg`
          })
        }
        this.loading = false
        this.page++
      }, 1000)
    },

    onScroll(e) {
      // 获取 div 元素的 scrollTop 和 clientHeight
      let scrollTop = e.target.scrollTop
      let clientHeight = e.target.clientHeight
      let scrollHeight = e.target.scrollHeight
      // 比较 scrollTop + clientHeight 和 scrollHeight
      if (scrollTop + clientHeight >= scrollHeight) {
        this.loadImages()
      }
    }
  }
}
</script>

In this example, we use v-scroll to listen to the scrolling event of the div element, and in the onScroll method Determine whether it has bottomed out. If it bottoms out, the loadImages method will be triggered. This method will simulate an asynchronous request for data and push the data into the images array. In addition, in order to improve user experience, we added a loading variable to prompt that data is loading in real time.

2. Use third-party plug-ins to implement rolling loading

In addition to writing code ourselves to implement rolling loading, we can also use some third-party plug-ins to implement rolling loading. Here we introduce two commonly used plug-ins, namely vue-infinite-scroll and vue-virtual-scroll-list.

  1. vue-infinite-scroll plug-in

vue-infinite-scroll is an infinite scroll plug-in based on Vue.js, which can help us implement scrolling loading lists , pictures and other scenes. Using this plug-in is very simple. You only need to add the v-infinite-scroll directive to the component that needs to implement rolling loading, and then specify the method that needs to trigger rolling loading.

The following is a sample code that uses the vue-infinite-scroll plug-in to implement a rolling loading list:

<template>
  <div class="list" v-infinite-scroll="loadMore">
    <div class="item" v-for="(item, index) in items" :key="index">
      {{ item.text }}
    </div>
  </div>
</template>

<script>
import InfiniteScroll from 'vue-infinite-scroll'

export default {
  mixins: [InfiniteScroll],

  data() {
    return {
      items: []
    }
  },

  methods: {
    loadMore() {
      // 模拟异步请求数据
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.items.push({ text: `Item ${this.items.length + 1}` })
        }
      }, 1000)
    }
  }
}
</script>

In this example, we first installed the vue-infinite-scroll plug-in through npm, and Introduce it into the component. We then use mixins to mix into the current component a Vue instance that automatically creates an infinite-scroll event that can be fired. Finally, we specify the loadMore method in the v-infinite-scroll directive, which simulates an asynchronous request for data and pushes the data into the items array.

  1. vue-virtual-scroll-list plug-in

vue-virtual-scroll-list is a virtual scrolling plug-in based on Vue.js that can help us quickly Implement list scrolling of large amounts of data to improve page performance and user experience. Different from traditional scroll loading, vue-virtual-scroll-list uses virtual scrolling technology to only render data items in the currently visible area, thereby avoiding a large number of DOM rendering and rearrangement, and improving the efficiency and smoothness of the page. Spend.

The following is a sample code that uses the vue-virtual-scroll-list plug-in to implement a scrolling loading list:

<template>
  <virtual-list
    :size="50"
    :remain="10"
    :data-key="'id'"
    :data-sources="items"
    :data-component="$options.components.item"
    @load="loadMore"
  >
  </virtual-list>
</template>

<script>
import VirtualList from 'vue-virtual-scroll-list'
import Item from './Item.vue'

export default {
  components: { Item },

  data() {
    return {
      items: []
    }
  },

  methods: {
    loadMore(start, end) {
      // 模拟异步请求数据
      setTimeout(() => {
        let count = end - start
        for (let i = 0; i < count; i++) {
          this.items.push({ id: this.items.length + 1, text: `Item ${this.items.length + 1}` })
        }
      }, 1000)
    }
  }
}
</script>

In this example, we first installed vue-virtual-scroll- through npm list plugin and introduce it into the component. We then use the component in the template, which accepts parameters such as size, remain, data-key, data-sources, and data-component.

Among them, the size parameter specifies the height of each data item, the remain parameter specifies the number of pre-rendering, data-key specifies the field used to uniquely identify each data item, and data-sources specifies the required Rendered data list, data-component specifies the rendering component of the data item. Finally, we execute the logic of asynchronously requesting data in the load event.

Conclusion

Through the above introduction, we can find that there are many ways to implement scrolling loading of images or lists in Vue.js. Although writing code yourself is flexible, it requires a lot of code and requires a certain amount of time and energy. Although using third-party plug-ins is simple, it requires an in-depth understanding of the principles and usage of plug-ins in order to better develop business. Therefore, when implementing rolling loading, you need to choose a method that suits you based on the specific business scenario and your own strength.

The above is the detailed content of How to implement scrolling loading of images or lists in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Laravel Vue.js single page application (SPA) tutorial Laravel Vue.js single page application (SPA) tutorial May 15, 2025 pm 09:54 PM

Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

How to work and configuration of front-end routing (Vue Router, React Router)? How to work and configuration of front-end routing (Vue Router, React Router)? May 20, 2025 pm 07:18 PM

The core of the front-end routing system is to map URLs to components. VueRouter and ReactRouter realize refresh-free page switching by listening for URL changes and loading corresponding components. The configuration methods include: 1. Nested routing, allowing the nested child components in the parent component; 2. Dynamic routing, loading different components according to URL parameters; 3. Route guard, performing logic such as permission checks before and after route switching.

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

What are the core differences between Vue.js and React in componentized development? What are the core differences between Vue.js and React in componentized development? May 21, 2025 pm 08:39 PM

The core differences between Vue.js and React in component development are: 1) Vue.js uses template syntax and option API, while React uses JSX and functional components; 2) Vue.js uses responsive systems, React uses immutable data and virtual DOM; 3) Vue.js provides multiple life cycle hooks, while React uses more useEffect hooks.

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

Vue responsive principle and solution to not trigger view updates when array updates? Vue responsive principle and solution to not trigger view updates when array updates? May 20, 2025 pm 06:54 PM

When Vue.js handles array updates, the view is not updated because Object.defineProperty cannot directly listen to array changes. Solutions include: 1. Use the Vue.set method to modify the array index; 2. Reassign the entire array; 3. Use the rewritten mutation method of Vue to operate the array.

What are the benefits of using key attributes (:key) with v-for directives in Vue? What are the benefits of using key attributes (:key) with v-for directives in Vue? Jun 08, 2025 am 12:14 AM

Usingthe:keyattributewithv-forinVueisessentialforperformanceandcorrectbehavior.First,ithelpsVuetrackeachelementefficientlybyenablingthevirtualDOMdiffingalgorithmtoidentifyandupdateonlywhat’snecessary.Second,itpreservescomponentstateinsideloops,ensuri

See all articles