Nuxt.js: Best Practices for Defining a Shared Method in the Mounted() Lifecycle Hook and Updating Component Data

I am trying to detect the scroll event within the mounted () of my component and update the component's data accordingly.

・component

<script>
import trackScroll from '~/utils/trackScroll'

export default {
  ...
  data() {
    return {
      scrollPosition: 0
    }
  },
  mounted() {
    window.addEventListener(
      'scroll',
      trackScroll(this.scrollPosition, window.scrollY)
    )
  },
</script>

・utils/trackScroll.js

export default function trackScroll(scrollPosition, scrollY) {
  scrollPosition = scrollY
}

There are a couple of issues in this scenario:

1. The function is only triggered once during the initial scroll, but I want it to be executed every time there is a scroll event.
2. The value of this.scrollPosition within the component remains unchanged despite the scrolling.

How can these problems be resolved?

Answer №1

The initial problem should not occur. By adding an event listener, it will trigger each time you scroll. I have tested this locally and it functions as intended. However, make sure to pass a function to the event listener instead of an already executed one.

You can return a result from the function and implement it like so:

export default function checkScroll(event) {
  return window.scrollY;
}

mounted() {
    window.addEventListener("scroll", event => {
      this.scrollPosition = checkScroll(event);
    });
  }

Check out this functioning example on CBS: https://codesandbox.io/s/0qjkoox68v

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

Retrieving Values Entered by Users in a Bootstrap Form

Here is the code I have for an input field within Bootstrap: <div class="form-group"> <label for="f2">F</label> <input type="text" class="form-control" name="f2" id="f2&quo ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

Transmitting data from Vue.js to an API endpoint

I am facing a challenge while attempting to send data to an API endpoint. The method I have in place to trigger this action seems to overlook the user ID and form data. Currently, I have a form that serves the purpose of updating user information through ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Issue with AJAX POST request, values not being passed to variables despite being displayed in the echo output

I am facing an issue with my Ajax post request, where the server seems to be receiving two date variables as empty even though they are sending correctly based on what I can see in the echo statement. The gettype function is returning NULL when trying to c ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Select a division and retrieve the identification of a different division

I am looking to trigger an event by clicking on one element and extracting the ID from a separate, unrelated div. Here is my attempt: $(".map_flag").on("click",function(){ var selectedID = ($(this).attr("data_modal")); $("#" + selectedID).fade ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

Connect CSS Transition to a click action

Below is the code snippet. When you click on the div, it creates a folding effect to the left. You can view it here. I want to link this effect to the arrows I use for sliding back and forth. For example: The left arrow should move the slide to the l ...

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

What is the best way to deploy a user interface update to a JavaScript frontend?

I am in the process of creating a basic react application that fetches multiple images and presents them as cards. The goal is to have an informational message displayed while the images are being loaded, and then remove the message once all the images ha ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Encountering the error message "Unable to access the key property of an undefined object" within a Vue template

Within my Vue application, I have a method that takes data, creates arrays, and then passes them to another Vue file for rendering in the template. The method looks like this: this.shoesData.titles = ['Date', 'Model', 'Pr ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Is there a way to effectively transfer cookie values from client-side services to server-side services in a React JS environment

I am struggling to fetch the value of cookies from a client service to a server service in React JS. The cookie is successfully stored on the client side, but when I try to console log it from the server side, it shows as undefined. Can someone please hel ...

CSS personalized by the user

I want to develop an application that allows users to input their customized CSS, which will then be implemented on the webpage. Is there a straightforward method to achieve this, or do I need to manually parse and modify the CSS by accessing elements like ...

Managing information retrieved from an asynchronous HTTP request

Here is the script I am using to load an HTML page generated by a node.js server: (function nodeLoader(){ $.ajax({ url: "http://oclock.dyndns.org:8000", method: "get", data: {hk: hk }, success: f ...

Guide on generating an instance of a component definition class within Angular 4

As a newcomer to Angular 4, I have been diligently learning through tutorials every day. However, despite extensive research, I am still struggling to grasp how to create an instance of a component class. Here is a snippet of the sample code I have been f ...

Activate Popover on Third Click with Bootstrap 4

Is it possible to create a button that triggers a popover after 3 clicks and then automatically dismisses after one click using Bootstrap v4.3.1? Code: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.mi ...

For the past 8 hours, my main focus has been on successfully transmitting a basic JSON object containing data from an API from my Express backend to a React component

I have been trying to achieve my initial goal of retrieving data from the API I am using on the backend, inserting that data into my database, and then sending that data through res.json so it can be accessed on the frontend via fetch. Despite all my attem ...