欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用vue3+ts+setup獲取全局變量getCurrentInstance的方法實(shí)例

 更新時(shí)間:2022年08月10日 10:24:12   作者:浩星  
這篇文章主要給大家介紹了關(guān)于使用vue3+ts+setup獲取全局變量getCurrentInstance的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue3具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

前言:

vue3的 setup中是獲取不到this的,為此官方提供了特殊的方法,讓我們可以使用this,達(dá)到我們獲取全局變量的目的,但是在使用typescript的時(shí)候,就會(huì)有一些新的問(wèn)題產(chǎn)生,這里來(lái)做一個(gè)整理。

vue3官方提供的方法

1、引入方法

import { getCurrentInstance } from 'vue'

2、定義變量,接到我們的方法

setup() {
    const { proxy } = getCurrentInstance()
}

3、main.js中定義我們的全局變量

app.config.globalProperties.$api = '111'

4、頁(yè)面中使用我們的全局變量

setup() {
    const { proxy } = getCurrentInstance()
    console.log(proxy.$api)
}

vue3+ts 使用官方方法遇到的問(wèn)題:

Property 'proxy' does not exist on type 'ComponentInternalInstance | null'

我在網(wǎng)上找的方法:網(wǎng)上資料入口

import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加斷言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

效果:不識(shí)別這種寫(xiě)法,不清楚是什么問(wèn)題。多方嘗試無(wú)果

最終我解決問(wèn)題的方法:         

我把類(lèi)型換成any,結(jié)果成功了,不知道原因,以后在查查資料

setup() {
   const { proxy } = getCurrentInstance() as any
}

補(bǔ)充:Vue3 getCurrentInstance與ts結(jié)合使用的問(wèn)題

vue3項(xiàng)目中,如果不用ts這樣使用是沒(méi)問(wèn)題的

const { proxy } = getCurrentInstance()

在ts中使用會(huì)報(bào)錯(cuò):報(bào)錯(cuò):...類(lèi)型“ComponentInternalInstance | null”

我們?cè)陧?xiàng)目中一般會(huì)用到很多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獲取全局變量?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論