You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js页面中Mousetrap绑定无法实现路由跳转求助

问题解决:Mousetrap回调中无法访问$router的问题

报错Uncaught TypeError: Cannot read properties of undefined (reading '$router')的核心原因是:Mousetrap绑定的回调使用了普通函数,此时函数内部的this指向的是Mousetrap的上下文,而非Vue组件实例,所以无法访问到组件上的$router对象。

以下是两种可行的解决方法:

方法一:使用箭头函数

箭头函数不会绑定自身的this,会继承外层作用域(即Vue组件实例)的this指向,直接修改代码如下:

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

方法二:提前保存组件实例的引用

在回调外部将组件实例的this存入变量,回调内部通过该变量访问$router:

mounted() {
  const vm = this;
  Mousetrap.bind("1 2", function () {
    console.log("It works");
    vm.$router.push("/pagename");
  });
}

两种方法都能让你正确访问到$router,实现页面跳转功能。

内容的提问来源于stack exchange,提问作者needhelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:20:27