日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

解决Vue3的undefined问题

發布時間:2023/12/16 vue 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 解决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.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)


我的問題是粗心問題,但有可能有人和我一樣 所以分享一下 具體的解決方法可以參考別的博主的(他們的會更加詳細)

總結

以上是生活随笔為你收集整理的解决Vue3的undefined问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。