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

Vue.js中Cannot read properties of undefined (reading 'push')错误解决求助

问题解决方法

核心错误原因

报错Cannot read properties of undefined (reading 'push')是因为**this.$router未被正确获取**,同时你的路由跳转写法和配置不匹配,这两个问题共同导致了错误。

具体修复步骤

1. 确保$router能被正确访问

  • 如果是Vue 2项目:
    先检查main.js里是否正确挂载路由:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import router from './router'
    import App from './App.vue'
    
    Vue.use(VueRouter)
    
    new Vue({
      router, // 必须把router挂载到Vue实例上
      render: h => h(App)
    }).$mount('#app')
    

    若组件里用了箭头函数导致this指向错误,把回调改成普通函数并绑定this:

    axios.post(`http://localhost:3000/api/chat`, this.chat)
      .then(function(response) {
        // 这里的this能正确指向组件实例
        this.$router.push(...)
      }).bind(this)
    
  • 如果是Vue 3项目(用<script setup>):
    不能直接用this.$router,需要手动导入useRouter钩子:

    import { useRouter } from 'vue-router'
    
    const router = useRouter()
    
    // 跳转时直接用router.push
    router.push({
      name: 'ChatRoom',
      params: {
        id: ...,
        nickname: ...
      }
    })
    

2. 修正路由跳转的写法

你的路由配置中name为ChatRoom,path是/chat-room/:id/:nickname,跳转时按以下两种方式修改:

  • 推荐:用name配合params(不会出错):
    this.$router.push({
      name: 'ChatRoom', // 用路由配置里的name,不是路径字符串
      params: {
        id: this.$route.params.id,
        nickname: response.data.nickname
      }
    })
    
  • 若用path,必须拼接完整路径,不能搭配params:
    this.$router.push(`/chat-room/${this.$route.params.id}/${response.data.nickname}`)
    

3. 额外检查

  • 确认组件是在<router-view>范围内渲染的,否则$router和$route不会被自动注入。
  • 若用了自定义封装或第三方组件,检查是否覆盖了this的指向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:42:23