溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue3之getCurrentInstance與ts怎么結合使用

發布時間:2023-04-20 17:22:04 來源:億速云 閱讀:188 作者:iii 欄目:開發技術

本篇內容主要講解“Vue3之getCurrentInstance與ts怎么結合使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Vue3之getCurrentInstance與ts怎么結合使用”吧!

getCurrentInstance與ts結合使用

vue3項目中,如果不用ts這樣使用是沒問題的

const { proxy } = getCurrentInstance()

在ts中使用會報錯:報錯:...類型“ComponentInternalInstance | null”

我們在項目中一般會用到很多getCurrentInstance()方法,直接封裝一下

創建useCurrentInstance.ts文件:

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

組件內使用:

<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報錯

vue3中沒有this + 各種api的方法 

vue3提供的方法,創建類似于this的實例。

const instance = getCurrentInstance() 

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

這種只適合本地調試,運行到線上就會報錯,報錯詳情為:

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

然后下面會報這個錯誤

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的結果,即:

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

到此,相信大家對“Vue3之getCurrentInstance與ts怎么結合使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女