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

Vue2升级Vue3时出现Cannot read properties of undefined(get)报错

解决思路

这个错误的核心是this.$http为undefined,导致无法调用get方法,原因是Vue3中全局属性的挂载和访问方式与Vue2不同,或者你使用的HTTP库(比如vue-resource)不兼容Vue3。以下是具体解决步骤:

  • 检查HTTP库兼容性:如果你之前用的是vue-resource,它已停止维护且不支持Vue3,必须替换为axios。先确保项目已安装axios:

    npm install axios
    
  • 修正全局挂载方式(选项式API):
    Vue2中你可能通过Vue.prototype.$http = axios挂载全局属性,但Vue3需要改为app.config.globalProperties:

    // main.js
    import { createApp } from 'vue'
    import axios from 'axios'
    import App from './App.vue'
    
    const app = createApp(App)
    app.config.globalProperties.$http = axios
    app.mount('#app')
    

    调整后,选项式API组件中的this.$http即可正常访问。

  • 推荐方案:直接导入axios使用:
    Vue3更推荐组件内直接导入依赖,避免全局挂载的隐式依赖,修改你的组件代码:

    import axios from 'axios'
    
    export default {
      // ...其他组件选项
      mounted() {
        Promise.all([
          axios.get('/api/v0/tickets/divisions')
            .then((response) => {
              this.customer.items = response.data;
            }),
          axios.get('/api/v0/hd/groups')
            .then((response) => {
              this.groups.items.push(...response.data);
              if (this.groups.selected.length === 0) this.groups.selected = this.groups.items
            }),
        ])
          .then(() => {
            this.timeScaleSelected();
          })
          .catch((e) => {
            console.error(e);
          });
      }
    }
    
  • 组合式API场景处理:如果你的组件使用<script setup>,this不存在,可通过getCurrentInstance()获取全局属性,或直接导入axios:

    import { getCurrentInstance, onMounted } from 'vue'
    import axios from 'axios'
    
    const { proxy } = getCurrentInstance()
    
    onMounted(() => {
      Promise.all([
        proxy.$http.get('/api/v0/tickets/divisions'),
        // 或直接使用 axios.get(...)
      ])
      // ...后续逻辑
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:52:51