Enhanced VS code typings for Nuxt injected properties

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?

Answer №1

@janeSmith

We found ourselves in a situation where we needed to utilize the project-vue.ts file for our project.

import Vue from 'vue';

export class ProjectVue extends Vue {
  $errorService: ErrorService
}

Subsequently, we had to extend it in various components like so:

export default MyComponent extends ProjectVue {}

While it can be cumbersome to remember to include everything in the ProjectVue class, it did prove effective for our needs.

Answer №2

I encountered a similar issue where I attempted to consolidate all my injected plugin types into a single file named vue-shim.d.ts. Placing it in the root folder as ~/vue-shims.d.ts, I declared all my types within that file like this: https://i.sstatic.net/HATOp.png

In summary, the solution is to include import '@nuxt/types' as suggested in a GitHub Issue here: https://github.com/nuxt-community/composition-api/issues/178#issuecomment-664844915

Furthermore, adding custom declaration type based on documentation found at:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

The JSX element 'SubscribeCard' does not contain any construct or call signatures

I'm looking to implement the react-subscribe-card module for handling email subscriptions in my react.js project. Below is the code snippet from my popup.tsx file: import React from "react"; import SubscribeCard from "react-subscribe-c ...

I am having trouble with the TypeScript compiler options not being detected in Visual Studio 2015

After creating an ASP.NET 5 Empty Website project in Visual Studio 2015, I set up a tsconfig.json file with the following settings: { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

Angular2: Ways to update components with resolver dependencies?

In my project, I have three separate components, each with its own resolver that retrieves data from distinct APIs. These components all depend on a shared URL provided by a service. My goal is to ensure that when the URL changes, each component refreshes ...

generateError('Circular reference found' + nodeRep)

Incorporating numerous charts in my application, I aim to manage all chart colors from the vuex store. Implementing the following code has allowed me to achieve this functionality. store.js import Vue from 'vue' import Vuex from 'vuex&apos ...

Creating multiple relationships in TypeORM for entities with private properties

In my node application, I am utilizing the typeorm library for entity mapping. My goal is to establish multiple type relations between entities. While following the documentation, I noticed that the entity properties are marked as public, allowing access f ...

Tips for setting a default checked radio button in Vuejs

Upon page load, the radio button status should initially be checked. Then, when the radio button is changed, a div below it should hide and show accordingly. I have attempted to write the code for this functionality, but unfortunately it is not working a ...

Several cucumber reports are showing an error message containing special characters

I am encountering an issue in the multiple cucumber report where error messages are being displayed with special characters. Is there a way to format them properly? I am currently learning Playwright, Typescript, and CucumberJs and generating reports for m ...

Alert box in Vue.js

Embarking on my journey with VueJS. I previously implemented an alert box using jQuery. Now, I am attempting to recreate that in VueJS. Here is my current progress: 1- Developed a component named NovinAlert.vue which includes: <template> & ...

The vue3-openlayers view remains consistently positioned at the bottom of the page

My perspective has shifted as illustrated below It seems like there is some padding within the view inside the map container causing the shift If I drag the map upwards, it disappears, but dragging it downwards keeps it visible I have custom controls at ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

The Azure function application's automatic reload feature does not function properly with the v4 model

Struggling to get Azure Function to recognize and incorporate changes in source code. I have set up a launch task to initiate the local server and run an npm script with tsc -w in watch mode. While I can see the modifications reflected in the /dist folder ...

What are the differences between an optional property and a non-optional property?

Let's say I am working on creating an array of type CoolObject. What would be the better approach if some objects have the property format, while others do not? // Option 1 export interface CoolObject { name: string; color: string; ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Tips for preventing the need to re-render every child component generated by the v-for directive

Here is a paragraph about the list of child components: <question-list-item v-for="(item, index) in questionListParsed" :key="item.id" :both-question="item" :class-id="classId" ...

The configuration of the property has not been declared (Error: <spyOnProperty>)

Imagine having a MenuComponent @Component({ selector: 'cg-menu', templateUrl: './menu.component.html', styleUrls: [ './menu.component.scss' ] }) export class MenuComponent implements OnInit { menu: MenuItem[]; isLog ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Elevate your Vue JS game by transforming two buttons into a streamlined select drop down menu

I currently have two buttons to sort my array either alphabetically or by relevance, and they are working well. I would like to change these options into a drop-down menu instead of separate buttons. How can I accomplish this? This is what I have right no ...