Vue3的Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘post’)

提示:在vue3的环境下利用axios发起请求

问题描述

提示:这里描述项目中遇到的问题:在利用this.$http方法发起请求时,却发现$http中的post是undefined

 methods:{
        // 点击重置对象  重置登录表单
        resetLoginForm(){
            // console.log(this);
            this.$refs.loginFormRef.resetFields()
            // console.log( this.$refs);
        },
        login() {
            console.log(this);
        this.$refs.loginFormRef.validate(async valid => {
          console.log(valid);
        if (!valid) return
        // 如果为true则发起请求此时需要配包
        const { data: res } = await this.$http.post('/login', this.loginForm)
        console.log(res)
        if (res.meta.code !== 200) return this.$message.error('登录失败!')
        this.$message.success('登录成功')
          })
        }
    }
        

原因分析:

(1)怀疑是在main.js中axios的挂载不成功
(2)怀疑是在login()中的使用方法不对
(3)怀疑是this的指向不正确


解决方案:

(1)在login()中打印this和this. h t t p 发 现 t h i s 的 指 向 无 问 题 , 但 t h i s . http发现this的指向无问题,但this. httpthisthis.http却是undefined
(2)在查询资料之后,发现可以从app.config.globalProperties的使用来解决问题。
从vue3的使用可以知道,想在添加一个可以在应用的任何组件实例中访问的全局 property,是通过以下的方法:

const Vue = createApp(App)
Vue.config.globalProperties.$http = axios

当在组件内调用http时需要使用getCurrentInstance()来获取。
需要注意的是,虽然proxy也可ctx代替,但ctx代替this只适用于开发阶段,如果将项目打包放到生产服务器上运行,就会出错,ctx无法获取路由和全局挂载对象的

import { getCurrentInstance} from "vue";
export default {
  setup( ) {
    const { proxy } = getCurrentInstance(); //获取上下文实例,proxy=vue2的this
  },
};

但是在使用了该方法却没解决问题。
再次进行检查之后,发现是注册实例的问题

const Vue = createApp(App)
Vue.config.globalProperties.$http = axios

{ createApp }.use(router).use(ElementPlus).mount('#app')

由以上代码可知真正全局挂载了$http的实例是Vue,但是login组件却在实例{ createApp }上,所以需要统一实例对象。如下

const Vue = createApp(App)
Vue.config.globalProperties.$http = axios
Vue.use(router).use(ElementPlus).mount('#app')

至此将post的undefined解决完毕。
但是post的undefined的一般解决方法是上面提到的getCurrentInstance()以及在vue3中this的使用(也会使用到getCurrentInstance()),下面做补充:

import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const _this= instance.appContext.config.globalProperties

这里的_this相当于vue2中的this
即_this.$http.post(’/login’, this.loginForm)


我的问题是粗心问题,但有可能有人和我一样 所以分享一下 具体的解决方法可以参考别的博主的(他们的会更加详细)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐