使用vue3+ts+setup獲取全局變量getCurrentInstance的方法實例
前言:
vue3的 setup中是獲取不到this的,為此官方提供了特殊的方法,讓我們可以使用this,達(dá)到我們獲取全局變量的目的,但是在使用typescript的時候,就會有一些新的問題產(chǎn)生,這里來做一個整理。
vue3官方提供的方法
1、引入方法
import { getCurrentInstance } from 'vue'
2、定義變量,接到我們的方法
setup() { const { proxy } = getCurrentInstance() }
3、main.js中定義我們的全局變量
app.config.globalProperties.$api = '111'
4、頁面中使用我們的全局變量
setup() { const { proxy } = getCurrentInstance() console.log(proxy.$api) }
vue3+ts 使用官方方法遇到的問題:
Property 'proxy' does not exist on type 'ComponentInternalInstance | null'
我在網(wǎng)上找的方法:網(wǎng)上資料入口
import { ComponentInternalInstance, getCurrentInstance } from 'vue'; // 添加斷言 const { proxy } = getCurrentInstance() as ComponentInternalInstance
效果:不識別這種寫法,不清楚是什么問題。多方嘗試無果
最終我解決問題的方法:
我把類型換成any,結(jié)果成功了,不知道原因,以后在查查資料
setup() { const { proxy } = getCurrentInstance() as any }
補(bǔ)充:Vue3 getCurrentInstance與ts結(jié)合使用的問題
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 } }
組件內(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>
總結(jié)
到此這篇關(guān)于使用vue3+ts+setup獲取全局變量getCurrentInstance的文章就介紹到這了,更多相關(guān)vue3 ts setup獲取全局變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue elementui表格獲取某行數(shù)據(jù)(slot-scope和selection-change方法使用)
這篇文章主要介紹了vue elementui表格獲取某行數(shù)據(jù)(slot-scope和selection-change方法使用),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01mockjs+vue頁面直接展示數(shù)據(jù)的方法
這篇文章主要介紹了mockjs+vue頁面直接展示數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12Vue?Router修改query參數(shù)url參數(shù)沒有變化問題及解決
這篇文章主要介紹了Vue?Router修改query參數(shù)url參數(shù)沒有變化問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09