這篇文章主要介紹“Vue3之getCurrentInstance與ts如何結合使用”,在日常操作中,相信很多人在Vue3之getCurrentInstance與ts如何結合使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Vue3之getCurrentInstance與ts如何結合使用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
成都創(chuàng)新互聯(lián)公司 - 四川樂山服務器托管,四川服務器租用,成都服務器租用,四川網(wǎng)通托管,綿陽服務器托管,德陽服務器托管,遂寧服務器托管,綿陽服務器托管,四川云主機,成都云主機,西南云主機,四川樂山服務器托管,西南服務器托管,四川/成都大帶寬,成都機柜租用,四川老牌IDC服務商
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中沒有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之getCurrentInstance與ts如何結合使用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
名稱欄目:Vue3之getCurrentInstance與ts如何結合使用
URL鏈接:http://aaarwkj.com/article16/ihhcdg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供響應式網(wǎng)站、企業(yè)網(wǎng)站制作、網(wǎng)頁設計公司、營銷型網(wǎng)站建設、小程序開發(fā)、標簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)