使用vue3+ts+setup獲取全局變量getCurrentInstance的方法實例
前言:
vue3的 setup中是獲取不到this的,為此官方提供了特殊的方法,讓我們可以使用this,達到我們獲取全局變量的目的,但是在使用typescript的時候,就會有一些新的問題產生,這里來做一個整理。
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'

我在網上找的方法:網上資料入口
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加斷言
const { proxy } = getCurrentInstance() as ComponentInternalInstance效果:不識別這種寫法,不清楚是什么問題。多方嘗試無果

最終我解決問題的方法:
我把類型換成any,結果成功了,不知道原因,以后在查查資料
setup() {
const { proxy } = getCurrentInstance() as any
}補充:Vue3 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+setup獲取全局變量getCurrentInstance的文章就介紹到這了,更多相關vue3 ts setup獲取全局變量內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue 獲取到數(shù)據(jù)但卻渲染不到頁面上的解決方法
這篇文章主要介紹了vue 獲取到數(shù)據(jù)但卻渲染不到頁面上的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11
如何使用Vue mapState快捷獲取Vuex state多個值
這篇文章主要為大家介紹了如何使用Vue mapState快捷獲取Vuex state多個值實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
在vue使用clipboard.js進行一鍵復制文本的實現(xiàn)示例
這篇文章主要介紹了在vue使用clipboard.js進行一鍵復制文本的實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01

