【发布时间】:2021-12-07 19:56:08
【问题描述】:
我有一个简单的Vue 3 + TypeScript repo,我正在尝试集成一个 Auth0 插件。
它在前端显示字符串化的user 对象,并且按预期工作。
但 Visual Studio Code 显示 TypeScript 错误 Cannot find name 'user'. ts(2304),因为它在 ...auth 扩展运算符中返回时看不到对象 user。
我不确定它为什么会这样,或者如何解决它。
这是 Auth0 插件的代码。简而言之,它使用app.provide("Auth", authPlugin); 提供对一堆东西的访问,包括user 对象:
import createAuth0Client, {
Auth0Client,
GetIdTokenClaimsOptions,
GetTokenSilentlyOptions,
GetTokenWithPopupOptions,
LogoutOptions,
RedirectLoginOptions,
User,
} from "@auth0/auth0-spa-js";
import { App, Plugin, computed, reactive, watchEffect } from "vue";
import { NavigationGuardWithThis } from "vue-router";
let client: Auth0Client;
interface Auth0PluginState {
loading: boolean;
isAuthenticated: boolean;
user: User | undefined;
popupOpen: boolean;
error: any;
}
const state = reactive<Auth0PluginState>({
loading: true,
isAuthenticated: false,
user: {},
popupOpen: false,
error: null,
});
async function handleRedirectCallback() {
state.loading = true;
try {
await client.handleRedirectCallback();
state.user = await client.getUser();
state.isAuthenticated = true;
} catch (e) {
state.error = e;
} finally {
state.loading = false;
}
}
function loginWithRedirect(o: RedirectLoginOptions) {
return client.loginWithRedirect(o);
}
function getIdTokenClaims(o: GetIdTokenClaimsOptions) {
return client.getIdTokenClaims(o);
}
function getTokenSilently(o: GetTokenSilentlyOptions) {
return client.getTokenSilently(o);
}
function getTokenWithPopup(o: GetTokenWithPopupOptions) {
return client.getTokenWithPopup(o);
}
function logout(o: LogoutOptions) {
return client.logout(o);
}
const authPlugin = {
isAuthenticated: computed(() => state.isAuthenticated),
loading: computed(() => state.loading),
user: computed(() => state.user),
getIdTokenClaims,
getTokenSilently,
getTokenWithPopup,
handleRedirectCallback,
loginWithRedirect,
logout,
};
const routeGuard: NavigationGuardWithThis<undefined> = (
to: any,
from: any,
next: any
) => {
const { isAuthenticated, loading, loginWithRedirect } = authPlugin;
const verify = async () => {
// If the user is authenticated, continue with the route
if (isAuthenticated.value) {
return next();
}
// Otherwise, log in
await loginWithRedirect({ appState: { targetUrl: to.fullPath } });
};
// If loading has already finished, check our auth state using `fn()`
if (!loading.value) {
return verify();
}
// Watch for the loading property to change before we check isAuthenticated
watchEffect(() => {
if (!loading.value) {
return verify();
}
});
};
interface Auth0PluginOptions {
domain: string;
clientId: string;
audience: string;
redirectUri: string;
onRedirectCallback(appState: any): void;
}
async function init(options: Auth0PluginOptions): Promise<Plugin> {
client = await createAuth0Client({
// domain: process.env.VUE_APP_AUTH0_DOMAIN,
// client_id: process.env.VUE_APP_AUTH0_CLIENT_KEY,
domain: options.domain,
client_id: options.clientId,
audience: options.audience,
redirect_uri: options.redirectUri,
});
try {
// If the user is returning to the app after authentication
if (
window.location.search.includes("code=") &&
window.location.search.includes("state=")
) {
// handle the redirect and retrieve tokens
const { appState } = await client.handleRedirectCallback();
// Notify subscribers that the redirect callback has happened, passing the appState
// (useful for retrieving any pre-authentication state)
options.onRedirectCallback(appState);
}
} catch (e) {
state.error = e;
} finally {
// Initialize our internal authentication state
state.isAuthenticated = await client.isAuthenticated();
state.user = await client.getUser();
state.loading = false;
}
return {
install: (app: App) => {
app.provide("Auth", authPlugin);
},
};
}
interface Auth0Plugin {
init(options: Auth0PluginOptions): Promise<Plugin>;
routeGuard: NavigationGuardWithThis<undefined>;
}
export const Auth0: Auth0Plugin = {
init,
routeGuard,
};
在我的Profile.vue 页面中,我使用const auth = inject<Auth0Client>("Auth")!; 注入Auth0 插件,并使用...auth 扩展运算符从setup() 返回其所有内容。这包括现在可以在模板中使用的 user 对象。
所有这些都在前端工作。它按预期显示字符串化的user 对象。
但是 vscode 抛出 Cannot find name 'user'. ts(2304) 错误,因为 user 对象没有从 setup() 显式返回。
似乎它不知道...auth 扩展运算符在auth 内部有user 对象:
<template>
<div class="about">
<h1>This is a profile page, only logged in users can see it.</h1>
</div>
<div class="row">
{{ JSON.stringify(user, null, 2) }} <!-- ERROR: Cannot find name 'user'.ts(2304) -->
</div>
</template>
<script lang="ts">
import { Auth0Client } from "@auth0/auth0-spa-js";
import { inject } from "vue";
export default {
name: "Profile",
setup() {
const auth = inject<Auth0Client>("Auth")!;
return {
...auth,
};
},
};
</script>
我试图通过显式返回user 对象来解决这个问题,如下所示,但它破坏了功能。字符串化的user 对象不再显示在前端:
<template>
<div class="about">
<h1>This is a profile page, only logged in users can see it.</h1>
</div>
<div class="row">
{{ JSON.stringify(auth_user, null, 2) }}
</div>
</template>
<script lang="ts">
import { Auth0Client } from "@auth0/auth0-spa-js";
import { inject } from "vue";
export default {
name: "Profile",
setup() {
const auth = inject<Auth0Client>("Auth")!;
const auth_user = auth.getUser(); // This does not work
//const auth_user = auth.user; // This variation also doesn't work
return {
auth_user,
};
},
};
</script>
谁能弄清楚这里发生了什么以及如何解决错误?
【问题讨论】:
标签: typescript vue.js visual-studio-code auth0 vue-composition-api