Using a javascript component in vue.js with typescript - a step-by-step guide!

I have created a component in one project and now I want to make it accessible for use in another project. This is how I am currently exposing it:

import ToastNotification from '../ToastNotification';
import Api from './api';

const VueToast = (Vue, options = {}) => {
  const methods = Api(Vue, options);
  Vue.$toast = methods;
  Vue.prototype.$toast = methods;
};

ToastNotification.install = VueToast;

export default ToastNotification;

In my index.js file I declare :

import VueToast from './toast/js/index';

Vue.use(VueToast);

However, when I npm install this project as a library in another project, the line this.$toast('message') is not recognized and shows an error, stating "Property '$toast' does not exist on type ''".

Interestingly, I was able to use 'this.$toast('')' within the original project, but facing issues when trying to do so in a different project. The component is built using Vue.js and JavaScript and I am attempting to integrate it into a TypeScript-supported Vue.js project.

I have also tried declaring it in the main.ts file of my project, but the issue persists:

import VueToast from'/src/components/toast/js/index';

Vue.use(VueToast);

Can you suggest what may be missing or needs to be declared differently?

Answer №1

If you want to include the $toast function in your Vue component instance, you can define the necessary type augmentation by following these steps in a .d.ts file (e.g., create a new file named custom-types.d.ts):

For Vue 2:

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $toast: (msg: string) => void;
  }
}

export {}

For Vue 3:

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $toast: (msg: string) => void;
  }
}

export {}

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

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

Navigating through routes based on identifiers

My goal is to dynamically display content based on the ID by generating the ID through my menu selection. I am facing challenges with setting up the ID properly. The channelName variable contains all the channels with different IDs. Upon clicking an item, ...

Error with Vimeo SDK: Mysterious Player Issue Post Setup (VueJS)

I have a requirement to showcase multiple videos on a Vue-powered website using a Vimeo player. To achieve this, I have developed a VideoPlayer component specifically designed for each video: <template> <div class="video-element__containe ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

What is the best way to implement conditional styling in Vue.js?

Looking to incorporate a conditional style into my Component. Here is my component: <site-pricing color="primary" currency="$" price="25" to="/purchase" > <template v-slot:title>Complete</templat ...

Vue - The compilation process encountered an error (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): SyntaxError: An unexpected token was found (13:1080)

When attempting to run the command "cross-env NODE_ENV=development nodemon ./server.js", I encountered the following error: ModuleBuildError: Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): SyntaxError: Unexpected to ...

What is the best way to execute an asynchronous request within a CanDeactivateFn guard in Angular?

Here's a strange question I've been grappling with lately. So, I've got this function that essentially creates a custom Alert Window to handle unsaved form data when a user tries to navigate away. It may or may not be triggered depending on ...

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

Ways to stop user authentication in Firebase/Vue.js PRIOR to email verification

I am currently working on a Vue.js and Firebase authentication interface with an email verification feature. The setup is such that the user cannot log in until they click the verification link sent to the email address provided during the login process. ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Display only the latest upload using the v-for loop

Our application requires users to upload a copy of their driver's license to their profile. If they need to update their license, they can upload another one. However, users should only see their most recent upload. This is achieved using a v-for loo ...

Tips for embedding variables in a string using VueJS

I'm looking for a way to interpolate a string in VueJS that includes variables and HTML. Is there a method in Vue that allows for this? component.vue <template> <div v-html="test1"></div> </template> <script> expo ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...