Creating an endless scroll feature to dynamically render a list in Vue.js, displaying only visible items

With a very large array of objects and abundant data to render in Vue components on the DOM, the ideal approach is to only render the visible HTML. For instance, if each component is 100px in height and the container is 1000px tall, it makes sense to render only 10 components at a time. As the user scrolls down or up, elements can be rendered and "unrendered" in a FIFO (first in, first out) manner.

Which method would work best for this? One solution could involve utilizing an array of 10 objects and adding 100px to the container's height (with an extra 50px top and bottom). This way, when the user scrolls within that additional space, the FIFO action can be performed. Another possibility is to grant each component the ability to calculate (assisted by the window object) if it's visible and then proceed to render itself using a v-show directive. There are several potential approaches to tackle this issue.

(Please note that this question pertains specifically to dynamically rendering a list, rather than dynamically loading components.)

If you have any ideas, methodologies, standards, or techniques that could be helpful in this context, please feel free to share them!

var app = new Vue({
  el: '#app',
  data: {
    users: Array(1000).fill({
      gender: "male",
      name: {
        title: "mr",
        first: "vincent",
        last: "ouellet"
      },
      location: {
        street: "6963 disputed rd",
        city: "brockton",
        state: "yukon",
        postcode: "Z4J 0J2",
        coordinates: {
        latitude: "-60.8550",
        longitude: "-36.0196"
      },
      timezone: {
        offset: "+3:30",
        description: "Tehran"
      }
      },
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c1a05020f09021842031909000009182c09140d011c0009420f0301">[email protected]</a>",
      login: {
        uuid: "eb9b61f7-fb0b-4731-9a1c-f4b2a7b3b6a9",
        username: "bigpeacock949",
        password: "nyjets",
        salt: "0TdUElhf",
        md5: "0fbc0edb70fda545f8838634f11f4be2",
        sha1: "f83e02d917721a1516b74937841b9c7f75a75d1e",
        sha256: "69e2c04bd4ccb43815b529a7182e1e59b9f788032b8197af54b9b6d3f907b8a3"
      },
      dob: {
        date: "1959-08-27T20:26:03Z",
        age: 59
      },
      registered: {
        date: "2013-10-20T04:51:58Z",
        age: 4
      },
      phone: "647-173-6604",
      cell: "544-306-1457",
      id: {
        name: "",
        value: null
      },
      picture: {
        large: "https://randomuser.me/api/portraits/men/13.jpg",
        medium: "https://randomuser.me/api/portraits/med/men/13.jpg",
        thumbnail: "https://randomuser.me/api/portraits/thumb/men/13.jpg"
      },
      nat: "CA"
      }
    )
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  <ul v-for="(user, i) in users">
    <li>
      <image :src="`https://randomuser.me/api/portraits/men/${i}.jpg`"/>
      <!-- IM THE REAL APLICATION THIS IS A VERY HEAVY UI -->
      <pre>{{user}}</pre>
    </li>
  </ul>
</div>

Answer №1

To detect the end of a document in your custom method, you can attach an event listener.

window.addEventListener('scroll', () => {
    let bottomOfWindow =
      document.documentElement.scrollTop + window.innerHeight ===
      document.documentElement.offsetHeight;

    if (bottomOfWindow) {
      axios.get(`https://randomuser.me/api/`).then(response => {
        this.items.push(response.data.results[0]);
      });
    }
  });

After receiving the response, add it to the array that you are iterating through. On mobile devices, remember to handle touch events instead of scroll events.

Alternatively, I highly recommend using , a user-friendly plugin that simplifies implementation for both mobile and desktop environments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on setting the focus of an input in a form field using ngIf

I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true inside the ngOnInit() method. export class InputOverviewExamp ...

Arranging Controls in a Grid in a Vertical Formation?

I have a Paper element with checkboxes in it. Here is the image of what I am talking about: https://i.stack.imgur.com/Epmk5.png Currently, the checkboxes are arranged horizontally, but I want them to be stacked vertically. The Paper element containing the ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

The chosen options are not appearing. Could this be a problem related to AngularJS?

I am working on setting up a dropdown menu in HTML that includes only the AngularJS tag. This dropdown menu will be used to populate another AngularJS dropdown menu. Below is the code for the first dropdown menu: <select class="form-control" ng-model=" ...

Finding the largest number that is less than a specified variable within an array

I have a JavaScript array and a variable, set up like this; var values = [0, 1200, 3260, 9430, 13220], targetValue = 4500; How can I efficiently find the largest value in the array that is less than or equal to the given variable? In the provided ex ...

Angular 2: Troubleshooting Issues with Observable Data Display

Looking to implement a RESTful call with Angular 2 that constantly updates whenever there are changes in the API. In my service, I've included an Observable to fetch data from the API: getData(): Observable<any[]> { return this.http.get(url) ...

What could be causing my PlaneGeometry to not cast a shadow?

I am currently utilizing three.js to develop a scene featuring a model. The scene includes a plane that the model is positioned on, as well as a spotlight illuminating the model. The model is comprised of various objects, all of which have been configured ...

Click on the input to add or remove a value

I have written a code where, on click, I insert an email address into a field. However, what I am trying to achieve is that upon the next click on the same field, it will remove the email if one already exists in the input. Below is my current code snippe ...

The program is displaying an array as 0 0 0 0 0 5 instead of the anticipated array

class ArrayPrint { static void arrayPrinter(int[] x) { for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } } public static void main(String... S) { int[] y = {3, 3, 4, 2, 7}; x = ne ...

Populate a Textbox Automatically using a Dropdown List

MVC 4 Changing multiple display fields based on DropDownListFor selection Having some issues trying to implement the solution mentioned above. It seems like there might be a problem with either my javascript code or the controller. JavaScript in View ...

Navigating through c arrays

Can a C struct, such as: typedef struct { double a; int8_t b[5]; int32_t c; } Foo; be effectively represented in Swift? (using fixed width integers for clarity, you can mentally replace with char and int) When bringing a C struct into Swift, ...

How can I access a method from another JavaScript file (service) in React JS's App.js to make API requests?

Just starting out with React js and trying to utilize REST API data. I've created a separate file named /shared/job-service.js for this purpose. My goal is to call a method from job-service.js in App.js and display the results on the UI. However, I&ap ...

What could be the reason behind the undefined return value of val()?

When I click a button, my script is supposed to get the value of the next hidden input field. However, it always returns "undefined". What could be causing this issue and why does val() return undefined? If I only try to select the element with next(' ...

The functionality of window.print() is not supported in Internet Explorer 11

My angular js app has a print functionality where an html page opens using the window.open method. public openNewWindow(html: string, title: string) { var popupWin = window.open('', '_blank', 'scrollbars=no,menubar=no,toolbar ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

Using destructuring repeatedly for a single object property

At times, I engage in nested destructuring, where I go more than one level deep. It can be risky, but I always make sure the property exists to avoid encountering an error of undefined. Recently, I came across this scenario: const { match: { ...

A guide on utilizing Java's Collections to organize a list filled with objects from a class

Struggling to figure out how to properly sort this list. When I attempt to use Collections.sort(mylist);, an error surfaces that is beyond my comprehension due to my beginner status in Java. Myclass x1 = new Myclass("8", "12"); Myclass x2 = new Myclass("6 ...

How can one decrease the size of a React project?

After running npx create-react-app my-app, the download was quick but then it took over an hour for the installation process to complete. Upon checking the size of the newly installed project, I found that the node_modules folder alone was a whopping 4.24 ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

While attempting to encrypt a private key in JavaScript using dotenv, I encountered an issue: TypeError - I was unable to read properties of undefined, specifically 'toHexString'

Welcome to encrypt.js const ethers = require("ethers"); const fs = require("fs-extra"); require("dotenv").config(); async function main() { const wallet = new ethers.Wallet(process.env.RRIVATE_KEY); const encryptedJsonKey ...