Home > front end >  Mousetrap bind won't work in a nuxt.js page
Mousetrap bind won't work in a nuxt.js page

Time:09-09

hi i hope somebody can help me. I want to redirect to a different page as soon as a certain sequence is typed. I get the "It works" in my console but it won't redirect. I get the error message

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

Here is my code

<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>

I use the Mousetrap library from https://craig.is/killing/mice btw.

Do you have some suggestions?

CodePudding user response:

Thank you for your answers!!! This did the trick for me. Changed it to an arrow function so 'this.$router' can be kept as vue instance.

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

CodePudding user response:

Using it like this solved OP's issue:

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