Having trouble calling the loginWithRedirect
function within the header.vue component using inject feature in Vue 3 and Typescript.
ERROR in src/components/global/HeaderMenu.vue:77:17 TS2339: Property 'loginWithRedirect' does not exist on type 'Auth0Plugin'. 75 | methods: { 76 | login() {
77 | this.auth.loginWithRedirect(); | ^^^^^^^^^^^^^^^^^ 78 | }, 79 | logout() { 80 | // this.$AuthPlugin.logout();
I'm a newbie to Typescript and facing challenges with the usage of inject
in the context of Typescript and Vue 3. The initial issue was addressed here. According to my interpretation, I followed these steps:
async function init() {
const AuthPlugin = await Auth0.init({
onRedirectCallback: (appState) => {
router.push(appState && appState.targetUrl ? appState.targetUrl : window.location.pathname);
},
clientId: 'xxxx',
domain: 'xxxx',
audience: 'xxxx'
});
const app = createApp(App);
// library.add(faLink, faUser, faPowerOff);
app
.use(AuthPlugin)
.use(router)
.use(BootstrapVue3)
.provide('authPlugin', AuthPlugin)
.mount('#app');
}
init();
In my header.vue
component, I aim to utilize loginWithRedirect
from auth index.ts. To achieve this, I included the following code snippet in components/header.vue...
Imported and set type
import { defineComponent } from 'vue';
import { inject } from 'vue';
import { Auth0 } from '@/auth';
export type TAuthPlugin = typeof Auth0;
Within the setup()
method of the same header.vue component...
setup() {
const auth = inject<TAuthPlugin>('Auth');
This seems to grant access to the login
method via this.auth
https://i.sstatic.net/9cF9C.png
However, when attempting to access this.auth.login
, an error occurs. Why is that?
src/components/global/HeaderMenu.vue:77:7
TS2532: Object is possibly 'undefined'.
75 | methods: {
76 | login() {
> 77 | this.auth.loginWithRedirect();
| ^^^^^^^^^
78 | },
79 | logout() {
80 | // this.$AuthPlugin.logout();
header.vue
<script lang="ts">
import { defineComponent } from 'vue';
import { inject } from 'vue';
import { Auth0 } from '@/auth';
export type TAuthPlugin = typeof Auth0;
export default defineComponent({
name: 'HeaderMenu',
inject: ['authPlugin'],
methods: {
login() {
this.auth.loginWithRedirect();
},
logout() {
// this.$AuthPlugin.logout();
this.$router.push({ path: '/' });
},
},
setup() {
const auth = inject<TAuthPlugin>('Auth');
return {
auth,
};
},
});
</script>
The content of the auth index.ts for reference.
(Content of auth index.ts - omitted)
1: Vue 3 with Typescript inject does not work as intended. Spread types may only be created from object types