Using the Mousetrap binding on a nuxt.js page may not be effective

Hey there! I'm trying to achieve a certain functionality where I want to redirect to a different page once a specific sequence is typed. Although I can see the message "It works" in my console, the redirection is not happening and instead, I am getting an error which says:

"Uncaught TypeError: Cannot read properties of undefined (reading '$router')"

Below is the code snippet I am using:

<script>
export default {
  head() {
    return {
      script: [
        {
          src: "js/mousetrap.min.js",
        },
      ],
    };
  },
  components: {},
  name: "IndexPage",
  mounted() {
    Mousetrap.bind("1 2", function () {
      console.log("It works");
      this.$router.push("/pagename");
      return;
    });
  },
};
</script>

Just a heads up, I am making use of the Mousetrap library from .

Any suggestions on how to resolve this issue would be highly appreciated!

Answer №1

Appreciate your input! Your solution worked perfectly for me. I made the change to an arrow function to maintain 'this.$router' as a Vue instance.

created() {
    Mousetrap.bind("1 2", () => {
      this.$router.push("/pagename");
    });
  }

Answer №2

This implementation successfully resolved the problem faced by the original poster:

mounted() {
    Mousetrap.bind("1 2", () => {
      this.$router.push("/pagename");
    });
  }

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

What is limiting me from utilizing the entire Google Calendar feed?

I currently have a public Google Calendar set up. My goal is to retrieve appointment data in JSON format from this calendar. When I utilize the following URL https://www.google.com/calendar/feeds/{calendar_id}%40group.calendar.google.com/public/basic?alt ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts? object { item: 1, users: [ {name: "A", age: "23"}, {name: "B", age: "24"}, {name: "Ä", age: "27"} ] ...

Using space as a separator for thousands when formatting integers

In an attempt to change the appearance of 1000 to resemble 10 000, I found numerous examples online on how to add a separator such as a comma or some StringLocal. However, I am looking for a way to use a space instead. Can anyone advise me on which locale ...

The Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

Ways to incorporate ng-app into an HTML element when HTML access is limited

In my current project, I am using Angular.js within a template system. The challenge I am facing is that I need to add ng-app to the html element, but I do not have direct access to do this on the page itself. Initially, my page structure looks like this: ...

Can the order of React lifecycle events be reliably predicted across different components?

Is there a clear documentation on the guarantees of React lifecycle order across separate components? For instance, if I have: <div>{ x ? <A /> : <B /> }</div> When x changes from true to false, one component will unmount and the ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

How to Monitor Store Changes within a Vue File Using Vue.js

I am working with 2 vue files, header.vue and sidebar.vue. Both components are imported into layout.vue. Here are the steps I am following: 1. Initially, when the page loads, I update the store in header.vue with some values inside the created hook. 2. ...

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Sharing data between two components on the same level in Vue.js

I have a situation where I need to transfer data from one component1 to another component2. I am not utilizing vuex or router for this task. The component tree looks like this: -Parent --Component1 --Component2 In the first component1, I am sending an ...

What are the correct steps for integrating C3JS into WebPack efficiently?

Currently, I am attempting to incorporate C3JS into my VUEJS/WebPack project (based on the boilerplate found here). D3JS is successfully loaded by npm installing it and including it as a webpack plugin. However, the same approach does not seem to work for ...

What is the best way to create a map in React that allows for changing the state without affecting all elements?

When working with a JSON file containing various values, one of them being "iframe" which can hold either "si" (yes) or "no" based on whether it should include an iframe. With this value (yes/no), I need (this.props.tabsiframe === 'yes') to deter ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

Tips on accessing close autoComplete/TextField title in AppBar

Looking to add a search bar and login button in the AppBar, where the search Bar is positioned close to the title. The desired order for the AppBar components should be as follows: Title SearchBox LoginButton How can this be achieved? Below is th ...

Encountering complications while attempting to launch Nuxt on Digital Ocean

I've been struggling to deploy my Nuxt application on Digital Ocean for some time now, following a specific tutorial to help me through the process. Link to Tutorial Despite my efforts, I keep encountering an error when trying to access the site: Th ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...