My approach to injecting properties into the Nuxt TS context is as follows:
~/plugins/services.ts
import Vue from 'vue';
import { errorService } from '~/services/error';
import { Plugin } from '@nuxt/types'
const services: Plugin = (context, inject) => {
inject('errorService', Vue.observable(errorService))
}
export default services
Next, I have a types file
~/plugins.d.ts
import Vue from 'vue';
import { ErrorService } from '~/services/error';
declare module 'vue/types/vue' {
interface Vue {
$errorService: ErrorService
}
}
declare module '@nuxt/types' {
interface NuxtAppOptions {
$errorService: ErrorService
}
interface Context {
$errorService: ErrorService
}
}
declare module 'vuex/types/index' {
// this.$myInjectedFunction inside Vuex stores
interface Store<S> {
$errorService: ErrorService
}
}
This is how it's used in a component
<template lang="pug">
div test
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
@Component({})
export default class ExampleComponent extends Vue {
mounted() {
this.$errorService.setErrorMessages('Failed to create meeting','Error message');
}
}
</script>
I've also shimmed the Vue files
~/shims-vue.d.ts
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
Everything is building with no issues. VS Code can read the type if it's used as this.$errorService
in a mixin within a .ts
file, but shows an error that this.$errorService
doesn't exist if it's in a .vue
file. Is there something else I need to do to make VS Code recognize the type in Vue files?