vue3 + ts + setupは、グローバル変数getCurrentInstanceを取得します

序文:

        これはvue3のセットアップでは使用できません。このため、オフィシャルは特別なメソッドを提供し、これを使用してグローバル変数を取得する目的を達成できますが、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が遭遇した問題:

プロパティ'proxy'はタイプ'ComponentInternalInstance|に存在しません ヌル'

 私がオンラインで見つけた方法:オンラインデータ入力

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

効果:このスペルは認識されず、問題が何であるかが明確ではありません。役に立たない複数の試み

最終的に問題に対する私の解決策:

        タイプをanyに変更しましたが、結果は成功しました。理由はわかりません。後で情報を確認します。

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

 

おすすめ

転載: blog.csdn.net/qq_41619796/article/details/122997704