I'm using Vue3 with TypeScript, the vue-property-decorator and vue-class-component package. I want to create global service class with vue provide. In theory, I will provide global service in main.ts, where I create my Vue instance.

Auth.service.ts

export class AuthService {
public constructor() {
    // do nothing
}

public login():{
  return axios.post()
}

main.ts

import { createApp } from 'vue'
import { AuthService } from '@/services/AuthService';
const app = createApp(App);
...
app.provide('authService', new AuthService());
app.mount('#app');

Login.component.ts

What is my expected result:

Expect to see the function being call from the login.vue

import { Vue } from "vue-class-component";
import { AuthService } from '@/services/AuthService';
import { Inject } from 'vue-property-decorator';

export default class Login extends Vue {

  @Inject('authService') private authService: AuthService;
}

What is my current result:

  • Error: 'Property 'authService' has no initializer and is not definitely assigned in the constructor.'

Please advice is that my current setup got any problem. Thanks so much

** UPDATE: I changed type of property authService from AuthService to any in Login.vue. It's worked.

@Inject('authService') private authService: any;

But I really want to define a type of authService like authService: AuthService in component Login.vue. How can I do that?

** Solution: I found a solution. @Inject('authService') private authService = new AuthService()

It's worked

0

There are 0 best solutions below