使用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
}補充: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項目的網(wǎng)絡(luò)請求代理到封裝步驟詳解
這篇文章主要介紹了Vue項目的網(wǎng)絡(luò)請求代理到封裝步驟,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
vue 獲取到數(shù)據(jù)但卻渲染不到頁面上的解決方法
這篇文章主要介紹了vue 獲取到數(shù)據(jù)但卻渲染不到頁面上的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
如何使用Vue mapState快捷獲取Vuex state多個值
這篇文章主要為大家介紹了如何使用Vue mapState快捷獲取Vuex state多個值實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
在vue使用clipboard.js進行一鍵復(fù)制文本的實現(xiàn)示例
這篇文章主要介紹了在vue使用clipboard.js進行一鍵復(fù)制文本的實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
vue中使用file-saver導(dǎo)出文件的全過程記錄
這篇文章主要給大家介紹了關(guān)于vue中使用file-saver導(dǎo)出文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02

