本篇內容主要講解“Vue3之getCurrentInstance與ts怎么結合使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Vue3之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中沒有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怎么結合使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。