Vue3之getCurrentInstance與ts結合使用的方式
getCurrentInstance與ts結合使用
vue3項目中,如果不用ts這樣使用是沒問題的
const { proxy } = getCurrentInstance()
在ts中使用會報錯:報錯:...類型“ComponentInternalInstance | null”
我們在項目中一般會用到很多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 ? ? } }
組件內使用:
<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提供的方法,創(chuàng)建類似于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+TS實現(xiàn)數(shù)字滾動效果CountTo組件
最近開發(fā)有個需求需要酷炫的文字滾動效果,發(fā)現(xiàn)vue2版本的CountTo組件不適用與Vue3,沒有輪子咋辦,那咱造一個唄,感興趣的小伙伴可以跟隨小編一起了解一下2022-11-11ElementUI 詳細分析DatePicker 日期選擇器實戰(zhàn)
這篇文章主要介紹了ElementUI詳細分析DatePicker 日期選擇器實戰(zhàn)教程,本文通過實例代碼圖文介紹給大家講解的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-08-08vue開發(fā)之LogicFlow自定義業(yè)務節(jié)點
這篇文章主要為大家介紹了vue開發(fā)之LogicFlow自定義業(yè)務節(jié)點,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01