Struggling with implementing TypeScript mixin in a Vue.js project?

I recently made the switch from Vue.js to TypeScript, but now I am facing an issue with using mixins in TypeScript. I tried two different types of mixins, but unfortunately, none of them worked for me and I keep getting error ts2339. I couldn't find a solution on https://v2.vuejs.org/v2/guide/typescript.html#Basic-Usage.

Here is the first mixin:

//mixin.ts
import {ViewState} from "@/types";
import {mocked_view_state} from "@/api/mock/profile.device.group.mock";

export const ProfileDeviceGroup = {
  methods: {
    resetViewState(): ViewState {
      return mocked_view_state;
    }
  }
};

And here is the second one:

//mixin.ts
import Vue from "vue";
import {ViewState} from "@/types";
import {mocked_view_state} from "@/api/mock/profile.device.group.mock";

const ProfileDeviceGroup = Vue.extend({
  methods: {
    resetViewState(): ViewState {
      return mocked_view_state;
    },
  }
});
export default ProfileDeviceGroup;

So, does anyone have any suggestions on how to resolve this problem?

..............

Update:

..............

After trying out vue-typed-mixins, the initial problem was resolved. However, a new issue has emerged as shown in the image below: https://i.sstatic.net/3tKJ8.png

Answer №1

Consider incorporating a package such as vue-typed-mixins or transitioning to the Vue"class component approach and utilizing implements.

@Component
export default class ComponentUsingMixins extends Vue implements MyMixin {}

If you are working with vue-property-decorator, it offers native support for mixins:

@Component
export default class ComponentWithMixins extends mixins(MyMixin) {}

Answer №2

After creating an issue on Vue-typed-mixins's GitHub page (https://github.com/ktsn/vue-typed-mixins/issues/4), it seems that the problem is not yet resolved and the author believes it should be addressed by Webstorm and Vuetr plugin developers, rather than being a Vue-typed-mixins issue. However, I still think that the problem may be related to the Vue-typed-mixins plugin. I remain hopeful that the issue will be fixed soon and would like to extend my gratitude to the author of Vue-typed-mixins, as well as the Webstorm and Vuetr teams.

For those, like myself, who are looking for solutions while working with Vue + Typescript, there appears to be a viable alternative in using the Vue2-composition-api. Some teams have reported success with this approach and assured me that it works well with TypeScript, eliminating the need for mixins altogether. Is Vuejs2.x composition api fully compatible with typescript?

Fingers crossed that it all comes together...

Answer №3

Just discovered something cool in the vue-router type definition file that allows you to globally add necessary types for your mixin by extending the ComponentCustomProperties interface within the @vue/runtime-core module.

To include all type definitions, simply add this to your mixin.ts file:

declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        initializeViewState: () => ViewState;
    }
}

I've tested this feature in vscode with vue3 single-file-components and occasionally had to reload the vscode window to apply all type changes to the runtime-core successfully.

Answer №4

Discovered a new method for obtaining typings for mixins in a Vue-TypeScript project using vue-property-decorator:

// your-mixin.ts
import Vue from "vue"
import { Component } from "vue-property-decorator"

@Component
export default class YourMixin extends Vue {
    // Ensure all properties and methods are public.
    // If there are certain properties that should not be altered, mark them as readonly
    public readonly test: string = "test"

    public get sampleNumber(): number {
       return 1
    }

    public sampleMethod(): void {
        
    }
}
// your-component.vue
import { Component, Mixins } from "vue-property-decorator"
import YourMixin from "@/mixins/YourMixin"

@Component
export default class YourComponent extends Mixins(YourMixin) {
    // For Components with only one mixin, no additional steps are needed,
    // but if there are multiple mixins, you must redefine the mixin properties without instantiation:

    public test!: string
    public sampleMethod!: CallableFunction

    // TypeScript may throw errors when setting a method's type as (arg: string) => void,
    // In such cases, use the generic CallableFunction instead of specifying the argument type
}

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

Firebase causing Nuxt async to fail on page reload

I'm encountering a problem with asyncData() when I refresh the page. On navigating from a list to a single item, it works fine. However, upon reloading the page, I see an empty object. In my page, I have the following code: <template> <di ...

What is the best way to transfer attributes from a sub-menu item to its parent in the hierarchy?

Recently, my employer made the decision to expand the menu bar by adding additional sub-pages. However, what used to work perfectly fine with just one sub-menu is now encountering issues due to the new sub-menu nested under another sub-menu. https://i.sst ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...

Tips for passing parameters from an anchor click event in TypeScript

Is it possible to send parameters to a click event from an anchor element, or should we not pass params at all? Here is the function I am using: const slideShow = (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => { console.lo ...

Error occurs after upgrading React app to vite due to node-fetch issue

I'm a bit perplexed by this issue. Transitioning the build tool to vite has been seamless except for encountering this error: No matching export in "node_modules/node-fetch/lib/index.mjs" for import "RequestInit" No matching expor ...

The Vue component fails to display the updated data even after the prop data has been modified

This is the parent component called abc.vue <v-card outlined class="mt-4"> <DetailsTable v-show="toggleClientData" :columnDefs="columnDefs" :rowData="rowData" /> </v-card> methods:{ aggridData() { let self = this; th ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

What is the best way to find the index of a row in a Bootstrap Vue table?

When working with a v-for in Vue, I typically do it like this: v-for="(test, index) in tests" Is there a way to achieve the same result using Bootstrap Vue? Specifically, how can I access the index of all TR elements? <b-table :items="items" :field ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

Tips for receiving an array input in a GraphQL resolver

My query variables contain an array of strings that I need to use as the ids parameter inside my resolver. Below is the relevant code snippet. People.resolver.ts import { Resolver, Query, Mutation, Args, } from '@nestjs/graphql'; import { Peopl ...

Implementing data sorting in Vue and ASP.NET: A beginner's guide

Looking to add a sorting function to a simple table in Vue.js that displays database data? Specifically, you want the sorting to be triggered by clicking on the table header labeled 'Jenis Barang'. Check out this table. For those interested, her ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

Definition file for mapbox-gl-draw in Typescript, also known as d.ts file

I attempted to define the mapbox-gl-draw project in a typed manner but unfortunately, I was unsuccessful. Can anyone provide some guidance on this? Here is how the javascript file looks: 'use strict'; var Setup = require('./src/setup&apos ...

Learning the process of dynamically binding an id to an HTML tag in Vue.JS

I am currently utilizing Bootstrap Vue for UI and attempting to implement a collapsing feature using this provided link For instance, using v-b-toggle.collapse-2 where the 2 represents a static id. However, I am interested in dynamically assigning this id ...

Typing input props based on conditions

I'm struggling to create parameters that rely on the type of field being transmitted. It's puzzling why the handler includes any type of arguments. type TInputType = 'text' | 'number' | 'date'; type THandler<V&g ...

Ionic 5 plugin not loading correctly on iOS devices

After installing the TextToSpeech Cordova Plugin on my Ionic App: "@ionic-native/text-to-speech": "^5.30.0", "cordova-plugin-tts": "^0.2.3", I incorporated it into my Vue file: import { Plugins } from "@capacit ...

Integrating social login using vue-authenticate with passport in a Node.js environment

I've been working on integrating Facebook login with vue-authenticate and passport. Successfully logged into my Facebook account, I obtained the 'Callback code' as well. Here is my callback URL: http://localhost:8080/auth/callback?code=AQD0 ...

Timed up 10-second countdown with vue.js

<html> <head> <meta charset="utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" ></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> < ...

NG0900: Issue encountered while attempting to compare '[object Object]'. Please note that only arrays and iterable objects are permitted for comparison

Experimenting with an Angular project where I am retrieving data from a Minecraft API and displaying it on my website. This is my first time working with Angular's HTTP requests. Encountered the following error code; NG0900: Error trying to diff &apo ...

Combining the power of Vue.js and .NET Core for a powerful M

I'm currently working on developing an application using .Net Core and Vue.js. My goal is to utilize Vue.js for data loading and binding without creating a Single Page Application (SPA). In my _layout.cshtml file, I have the following: <script&g ...