When using Vuejs, it's important to note that the DOM.getBoundingClientRect event does not trigger on window scroll events, but instead

Situation: I am currently developing an infinite scroll feature on a website. The goal is to load more rows in a table when the bottom of the table reaches the bottom of the viewport from outside of it.

Implementation: To achieve this, I first declared a 'windowHeight' variable in the data section. In the created lifecycle hook, I initialized this variable with 'window.innerHeight' and added a resize event listener on the window object to update the 'windowHeight' variable whenever the window is resized. Here's the code snippet:

data() {
  return {
    windowHeight: 0,
  }
}

created() {
  this.windowHeight = window.innerHeight;
  window.addEventListener('resize', () => {
    this.windowHeight = window.innerHeight
  })
}

Next, I defined a variable called 'topRect' and set it equal to the top position of a div element placed right after the table in the template. When the top position of that element is less than the window inner height, a method should be triggered to load more data. This part of the implementation looks like this:

Code Snippet:

data() {
  return {
    windowHeight: 0,
    topRect: 0,
    divAfterTable: '',
  }
}

created() {
  this.windowHeight = window.innerHeight;
  window.addEventListener('resize', () => {
    this.windowHeight = window.innerHeight
  })
}

mounted() {
  this.divAfterTable = document.querySelector(#div-after-table)
  this.topRect = this.divAfterTable.getBoundingClientRect().top;
  window.addEventListener('scroll', this.setClientRect)
  })
}

methods: {
  setClientRects() {
    this.topRect = this.divAfterTable.getBoundingClientRect().top;
  }
}

Template:

<template>
  <div class="table">
    <div class="table__container">
      <table class="table__fixture">
        <thead>
          <tr>
            <td>col 1</td>
            <td>col 2</td>
            <td>col 3</td>
          </tr>
        </thead>
        <tbody>
          <tr v-if="tableData.data" v-for="row in tableData" :key="row.id">
            <td>{{row.colOne}}</td>
            <td>{{row.colTwo}}</td>
            <td>{{row.colThree}}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div id="div-after-table"></div>
  </div>
</template>

The remaining parts of the code related to this feature are not mentioned here.

Expectation:

The 'setClientRect' method should trigger on scroll events and update the 'topRect' variable accordingly. However, it seems to only work when the window is resized. Interestingly, adding a console.log('it works') inside the 'setClientRects' method confirms that the method is being called, but the rest of the method does not function unless the window is resized.

Unusual Behavior and Pertinent Information:

I have a somewhat complex component structure in my project where I need to apply this functionality to two different components. Strangely enough, the feature works perfectly on one component but fails on another. The problematic component is nested within multiple router-views - a child route structure. Here is an overview:

<Root>
  <App>
    <Navbar>
    <News> router-view: /news <-- FUNCTIONING HERE

<Root>
  <App>
    <Navbar>
    <League> router-view: /league 
      <Statistics> router-view /league/statistics <-- NOT WORKING HERE

If you require additional information, please let me know.

Answer №1

It appears that document.querySelector is being used in this code snippet. Have you considered using this.$el.querySelector instead?

this.$el.querySelector

Another option to consider is utilizing Vue Refs, as outlined in Vue documentation. It's possible that I may have misunderstood the issue at hand.

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

A custom Mongoose schema attribute configured with distinct values

I've been working on some code and here is what I have: var userSchema = new mongoose.Schema({ email: String, password: String, role: Something }); I'm aiming to set specific values ('admin', 'member', 'guest&apos ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

create a new Vuex.Store and include Mutations

Having trouble using the commit method as described here. I suspect it's because I'm using export default new Vuex.Store instead of export const store = new Vuex.Store. However, when I make this change, I encounter an issue similar to the one in ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Angular.js Issue: Repeating elements must be unique - Index tracking not functioning properly

I have been following a tutorial on the Ionic Framework, which utilizes Angular JS to develop a basic Todo application. The app adds a new task by utilizing the .push() method to append a new task object to an array of task objects. An issue arises when a ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

Tips for updating a value in a nested directive in AngularJS

My directive includes a menu toggle button and various nested directives with their own menus. The outer directive has an isolated scope, while the inner directive has no specified scope. I am trying to figure out how to show/hide the menu in the inner d ...

A JavaScript AddEventListener will not execute a function that has parameters

Attempting to execute a function with two parameters in NuxtJS upon clicking an element using AddEventListener. async handleSubmit(recipe, userRating) {some code...} setup(recipe) { document.querySelectorAll('.recipe-rating > .star').forEac ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Troubleshooting: Page Unable to Import/Execute Linked JavaScript on WebStorm with Node.js Backend

I've been following W3School's jQuery tutorial, but I'm encountering some issues with importing scripts to an HTML document hosted on a Node server in WebStorm. I have properly installed and enabled the jQuery libraries under Preferences &g ...

Tips for transferring a jQuery instance to a selector

Can someone help me with using .eq() instead of :eq() I would like to use the following syntax -> $('div').eq(1) Here is the code snippet I need help with: $(document).on('click', 'li.trigger div:eq(1) a.ajax img,' + ...

Ways to prevent adding duplicate elements to a state array in React.js?

The state provided below is within my class component. I need to prevent adding duplicate objects to an array in my state as shown below: this.state = { frequency: { time: [ {time:"20:15",timezone:"IST"}, ...

Omit the checkbox for children when clicking

I am encountering a problem with the following HTML code: <tr class="clickable" onclick="location.href='https://www.w3schools.com'"> <td> Lore ipsum </td> <td>More content</td> <td>< ...

Can you please tell me the title of my Vue component?

Currently experimenting with Vue for a small project. Initially, I was only using client code. As such, when I ran const mv = new Vue({...}); I could access the component externally using mv. Now that I'm utilizing Vue.cli, I define my component w ...

Troubleshooting Multer to fix image payload issues in a Node.js and React.js application

Currently, I am facing an issue while trying to send an image from my ReactJS frontend to my NodeJS Express backend using formData. Despite seemingly correct data transmission, the image does not appear in the payload and triggers this error from the backe ...

Angular is having trouble finding the Gapi object

I have implemented the integration of google-docs into my application using Angular. I referred to the google-docs API link provided in the Javascript format https://developers.google.com/docs/api/quickstart/js <!DOCTYPE html> <html> <hea ...

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...