欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Vue3之getCurrentInstance與ts如何結(jié)合使用

這篇文章主要介紹“Vue3之getCurrentInstance與ts如何結(jié)合使用”,在日常操作中,相信很多人在Vue3之getCurrentInstance與ts如何結(jié)合使用問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Vue3之getCurrentInstance與ts如何結(jié)合使用”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

成都創(chuàng)新互聯(lián)公司 - 四川樂(lè)山服務(wù)器托管,四川服務(wù)器租用,成都服務(wù)器租用,四川網(wǎng)通托管,綿陽(yáng)服務(wù)器托管,德陽(yáng)服務(wù)器托管,遂寧服務(wù)器托管,綿陽(yáng)服務(wù)器托管,四川云主機(jī),成都云主機(jī),西南云主機(jī),四川樂(lè)山服務(wù)器托管,西南服務(wù)器托管,四川/成都大帶寬,成都機(jī)柜租用,四川老牌IDC服務(wù)商

getCurrentInstance與ts結(jié)合使用

vue3項(xiàng)目中,如果不用ts這樣使用是沒(méi)問(wèn)題的

const { proxy } = getCurrentInstance()

在ts中使用會(huì)報(bào)錯(cuò):報(bào)錯(cuò):...類(lèi)型“ComponentInternalInstance | null”

我們?cè)陧?xiàng)目中一般會(huì)用到很多getCurrentInstance()方法,直接封裝一下

創(chuàng)建useCurrentInstance.ts文件:

import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const proxy = appContext.config.globalProperties
    return {
        proxy
    }
}

組件內(nèi)使用:

<script lang="ts">
import { defineComponent } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
export default defineComponent({
  setup() {
    const { proxy } = useCurrentInstance();
    console.log(proxy);
  },
});
</script>

vue3+ts使用getCurrentInstance報(bào)錯(cuò)

vue3中沒(méi)有this + 各種api的方法

vue3提供的方法,創(chuàng)建類(lèi)似于this的實(shí)例。

const instance = getCurrentInstance() 

const a1= getCurrentInstance();
a1.$toast({type: 'error', text: '登錄失敗' });

這種只適合本地調(diào)試,運(yùn)行到線(xiàn)上就會(huì)報(bào)錯(cuò),報(bào)錯(cuò)詳情為:

類(lèi)型“ComponentInternalInstance | null”上不存在屬性“proxy”。ts(2339)

然后下面會(huì)報(bào)這個(gè)錯(cuò)誤

Unsafe member access .$axios on an `any` value.  eslint@typescript-eslint/no-unsafe-member-access

Unsafe call of an `any` typed value.  eslint@typescript-eslint/no-unsafe-call

原因:

getCurrentInstance()的返回類(lèi)型存在null所以在此處添加斷言即可。

在proxy后面添加?來(lái)過(guò)濾null的結(jié)果,即:

const instance = getCurrentInstance()?.proxy  
 instance ?.$toast('請(qǐng)xxx!')

到此,關(guān)于“Vue3之getCurrentInstance與ts如何結(jié)合使用”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

名稱(chēng)欄目:Vue3之getCurrentInstance與ts如何結(jié)合使用
URL鏈接:http://chinadenli.net/article16/ihhcdg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站企業(yè)網(wǎng)站制作網(wǎng)頁(yè)設(shè)計(jì)公司營(yíng)銷(xiāo)型網(wǎng)站建設(shè)小程序開(kāi)發(fā)標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)