Vue3 - 如何访问组合设置 API 中的全局属性?

问题描述 投票:0回答:1

我是 Vue 的新手。 文档说“setup”组合 API 很可能是将来支持的 API,所以我尝试在任何地方使用这种形式。

我想使用插件,但我不知道如何以设置 API 格式访问它。

这里是提供的示例,说明如何在 Composition API 中执行此操作:

const authCode = await this.$gAuth.getAuthCode();

当我尝试以组合 API 的设置形式使用该插件时,出现错误

"Cannot read properties of undefined (reading '$gAuth') "

产生该错误的 LOC 如下所示:

<script setup lang="ts">
... stuff ...
const googleUser = await this.$gAuth.signIn();

我的 main.ts 看起来像这样:

import gAuthPlugin  from "vue3-google-oauth2";

app.use(gAuthPlugin , {
  clientId: "768834812579-ivi0oopbkqe05cg6t41p83t7gteekut6.apps.googleusercontent.com",
  scope: "email",
  prompt: "consent",
  fetch_basic_profile: false,
});

我可以看到该插件正在定义一个全局属性(here),Vue 文档说可以在应用程序内的任何组件实例上访问该属性。

但是文档仅显示了组合示例(无需设置),我无法计算出其语法。这与这个被否决的答案的评论中提出的问题非常相似(实际的答案对我没有帮助)。

vue.js vuejs3
1个回答
0
投票

你不能。一些包(例如 vue-router)为组合 API 提供了另一种访问方法,即 useRoute()、useRouter()。如果您使用的东西没有提供这样的功能,最好的选择可能是在您的应用程序设置中自己提供注入的值:

const app = createApp(App);
app.use(gAuthPlugin, { ... });
app.provide('gAuth', app.config.globalProperties['$gAuth']);

用途:

import { inject } from 'vue';
const gAuth = inject('gAuth');
© www.soinside.com 2019 - 2024. All rights reserved.