In Vue js, the keydown listener does not have access to methods and data values

In the mounted function of my code, I have this:

 mounted () {
    document.addEventListener('keydown', function (e) {
      switch (e.keyCode) {
        case 37 :
          alert(this.indexPictures)
          break
      }
    })
  }

In my data value:

  data: function () {
    return {
      indexPictures: this.index,
    }
  },

The result I am getting is undefined.

I am facing an issue where I can't retrieve the value in the data function and the same problem occurs when attempting to access methods. The result I get is 'is not a function'.

Do you have any thoughts on what could be causing this?

Answer №1

Uncertain about the purpose of this.index, but assuming it is a prop or something similar.

Try eliminating the use of the keyword function from the addEventListener.

 mounted () {
    document.addEventListener('keydown', (e)=> {
      switch (e.keyCode) {
        case 37 :
          alert(this.indexPictures)
          break
      }
    })
  }

While not directly related to the issue, also remove the function keyword from data:

data() {
    return {
      indexPictures: this.index,
    }
  },

The presence of the function keyword alters the scope, causing this to be bound to the function itself (in your scenario, the callback). When using an arrow function, the this keyword corresponds to that in mounted, allowing access to your data.

As per MDN documents:

Arrow functions provide significant advantages, particularly with methods like setTimeout() and EventTarget.prototype.addEventListener(), which typically necessitate closure, call, apply, or bind for ensuring proper execution within the correct scope.

Remember, if this is a component segment, consider removing the listener before component destruction.

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

How should one properly import esm/dist modules in React/javascript?

Incorporating the geist component library into our codebase has been a significant step for us. However, as this library adds 250kb to our bundle, it's affecting our page speed. To address this issue, the usual recommendation is to only import what is ...

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

Fade in only a single element from a specific class using Jquery

I recently attempted to create a script that would fade in a tooltip when hovering over a link or image. Everything was working fine except for the fact that only one tooltip would appear at a time. In other words, I wanted to hover over an image and have ...

Differences between AngularJS template and templateURL when used in directives

Here is how I have defined a directive: app.directive('itemComments', ['ajax', function(ajax) { return { restrict: 'A', templateUrl: URL + 'public/Pages/Homepage/ajax/getCommentsTpl', ...

Displaying inner words in an array vertically using Vue JS

I'm facing an issue with the positioning of time elements in my array on the browser. They are currently located at the bottom, but I need them to be displayed on the sides. I attempted to solve this problem using CSS, but without success. Then, I tri ...

Tips for preparing data prior to downloading it as a CSV file

Trying to export data as a CSV file, encountering an issue with the generated file content: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[ ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified? class PositionCtrl { ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

Retrieve information from a mysql database and incorporate it into a javascript program

I am attempting to extract data from a MySQL database and utilize it in JavaScript. I stumbled upon this resource which was quite helpful, however, I am facing difficulties in displaying the information (as I have limited experience with jQuery). I suspect ...

The tooltip element positioned absolutely is being cut off by a container with overflow set to auto

How can I prevent a tooltip from being cut off by an overflow container within a modal? The modal-dialog needs to handle content overflow, so simply removing the "overflow: auto" property is not an option. body { margin: 0; } .container { display: ...

Tips for effectively utilizing "Session" in jQuery

Are there any comparable features in jQuery to Session["Param"] in C#? How can I implement it? I've looked up "sessionStorage" in jQuery, but I'm having trouble grasping it. ...

Utilizing Mongoose Schema across various endpoints in an Express application

As a newcomer to Node.js, I am using Mongoose and Express for my project. Within the routes/index.js file, I have defined a userDataSchema as follows: var Schema = mongoose.Schema; var userDataSchema = new Schema({ username: String, username_lower: ...

Only retrieve links that don't have the specified class by using regular expressions

I am trying to extract all links from an HTML document using REGEX, except for those with a specific class name. For example: <a href="someSite" class="className">qwe</a> <a href="someSite">qwe</a> My goal is to only capture the ...

What steps can be taken to rectify the issue with the table during the export to

I am using a library called DataTable to present my data in a table format. The DataTable has buttons on the header, one of which allows exporting the data into an Excel file. However, when I try to open the exported data in Excel, I encounter an error sta ...

Preventing loss of context in jQuery ajax when mixing HTML/JS and opening a <script> tag

I've encountered a situation where I'm using ajax to communicate with the backend, which is responding with a mix of HTML and JavaScript code. To load this content into a div, I'm using the html() function like so: $("#mydiv").html(ajaxRespo ...

What is the reason for the Web worker creating a new Class Instance every time a module is imported?

We are currently running a time-consuming function on a web worker. In addition, we have a Dispatcher Class that creates a single instance for other classes to utilize, as shown below: class Dispatcher { constructor() { console.log("calling"); ...

Scrollmagic - Creating dynamic effects by animating body and div backgrounds using multiple tweens

I'm currently developing a website that utilizes scrollmagic to smoothly transition the color of the active div (each set to size of the screen) from black back to white as you scroll down. The issue I am facing is that the body background color does ...

Can we trust the accuracy of Function.prototype.toString for our needs?

Can I trust Function.prototype.toString to provide a valid javascript function string for user-defined functions? Do any popular javascript engines differ in how they represent function objects as strings? I came across this question, but it doesn't ...

What is the best way to transfer text from a paragraph element to an input field without triggering a page refresh?

I have a challenge where I want to replicate the content of a <p> element into an <input> element's value attribute. The text within the paragraph includes values like .30, .31, .6, .38, which are dynamically updated by a jQuery script wi ...