Vue3之getCurrentInstance與ts結(jié)合使用的方式
getCurrentInstance與ts結(jié)合使用
vue3項(xiàng)目中,如果不用ts這樣使用是沒問題的
const { proxy } = getCurrentInstance()在ts中使用會(huì)報(bào)錯(cuò):報(bào)錯(cuò):...類型“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中沒有this + 各種api的方法
vue3提供的方法,創(chuàng)建類似于this的實(shí)例。
const instance = getCurrentInstance()?
const a1= getCurrentInstance();
a1.$toast({type: 'error', text: '登錄失敗' });這種只適合本地調(diào)試,運(yùn)行到線上就會(huì)報(bào)錯(cuò),報(bào)錯(cuò)詳情為:
類型“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()的返回類型存在null所以在此處添加斷言即可。
在proxy后面添加?來過濾null的結(jié)果,即:
const instance = getCurrentInstance()?.proxy ?
?instance ?.$toast('請(qǐng)xxx!') ?總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue如何實(shí)時(shí)往數(shù)組里追加數(shù)據(jù)
這篇文章主要介紹了vue如何實(shí)時(shí)往數(shù)組里追加數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue利用自定義指令實(shí)現(xiàn)按鈕權(quán)限控制
這篇文章主要為大家詳細(xì)介紹了Vue如何利用自定義指令實(shí)現(xiàn)按鈕權(quán)限控制效果,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,需要的可以參考下2023-05-05
vue 做移動(dòng)端微信公眾號(hào)采坑經(jīng)驗(yàn)記錄
這篇文章主要介紹了vue 做移動(dòng)端微信公眾號(hào)采坑經(jīng)驗(yàn)記錄,文中是小編記錄的三個(gè)坑及解決方案,需要的朋友可以參考下2018-04-04
Vue3+TS實(shí)現(xiàn)數(shù)字滾動(dòng)效果CountTo組件
最近開發(fā)有個(gè)需求需要酷炫的文字滾動(dòng)效果,發(fā)現(xiàn)vue2版本的CountTo組件不適用與Vue3,沒有輪子咋辦,那咱造一個(gè)唄,感興趣的小伙伴可以跟隨小編一起了解一下2022-11-11
ElementUI 詳細(xì)分析DatePicker 日期選擇器實(shí)戰(zhàn)
這篇文章主要介紹了ElementUI詳細(xì)分析DatePicker 日期選擇器實(shí)戰(zhàn)教程,本文通過實(shí)例代碼圖文介紹給大家講解的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-08-08
vue.js iview打包上線后字體圖標(biāo)不顯示解決辦法
這篇文章主要介紹了vue.js iview打包上線后字體圖標(biāo)不顯示解決辦法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn)
這篇文章主要為大家介紹了vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

