解决Vue3的undefined问题
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.http發現this的指向無問題,但this.http發現this的指向無問題,但this.http發現this的指向無問題,但this.http卻是undefined
(2)在查詢資料之后,發現可以從app.config.globalProperties的使用來解決問題。
從vue3的使用可以知道,想在添加一個可以在應用的任何組件實例中訪問的全局 property,是通過以下的方法:
當在組件內調用http時需要使用getCurrentInstance()來獲取。
需要注意的是,雖然proxy也可ctx代替,但ctx代替this只適用于開發階段,如果將項目打包放到生產服務器上運行,就會出錯,ctx無法獲取路由和全局掛載對象的
但是在使用了該方法卻沒解決問題。
再次進行檢查之后,發現是注冊實例的問題
由以上代碼可知真正全局掛載了$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()),下面做補充:
這里的_this相當于vue2中的this
即_this.$http.post(’/login’, this.loginForm)
我的問題是粗心問題,但有可能有人和我一樣 所以分享一下 具體的解決方法可以參考別的博主的(他們的會更加詳細)
總結
以上是生活随笔為你收集整理的解决Vue3的undefined问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Surface Go1 与Surface
- 下一篇: 如何使用 JS 实现带字母的导航城市列表