The correct way to incorporate a global property into a component template (using Vue 3, Vite, TypeScript, and the Composition API)

The component's property is not functioning properly

https://i.sstatic.net/qaUG9.png

src/main.ts

import { createApp } from 'vue'
import languagePlugin from '@/plugins/languagePlugin'
import App from './App.vue'

const app = createApp(App)
app.use(languagePlugin)
app.mount('#app')

./src/plugins/languagePlugin.ts

import { App } from 'vue'

export default {
    install(app: App) {
        app.config.globalProperties.$t = (key: string): string => key
    }
}

package.json

{
  ...
  "type": "module",
  ...
  "dependencies": {
    ...
    "vue": "^3.2.47"
  },
  "devDependencies": {

    "@types/node": "^18.15.3",
    "@vitejs/plugin-vue": "^4.1.0",
    "@vue/eslint-config-typescript": "^11.0.2",
    "eslint": "^8.36.0",
    "eslint-plugin-vue": "^9.9.0",
    "typescript": "^4.9.5",
    "vite": "^4.2.0",
    "vue-tsc": "^1.2.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": false,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "types": [
      "vite/client"
    ],
    "lib": [
      "ESNext",
      "DOM"
    ],
    "skipLibCheck": true,
    "noEmit": true,
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue"
  ],
  "references": [
    {
      "path": "./tsconfig.node.json"
    }
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "vite.config.ts"
  ]
}

./src/vite-env.d.ts

/// <reference types="vite/client" />

interface ImportMetaEnv {
    readonly VITE_APP_NAME: string
    readonly VITE_API_URL: string
}

interface ImportMeta {
    readonly env: ImportMetaEnv
}

./shims-vue.d.ts

declare module '*.vue' {
    import { defineComponent } from 'vue'
    const Component: ReturnType<typeof defineComponent>
    export default Component
}

./shims-vue-runtime-core.d.ts

export {}

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $t(key: string): string
    }
}

Answer №1

The problem was resolved by rebuilding the application

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $t(key: string): string
    }
}

Answer №2

Make sure to include the '$t' variable in your main.ts file for it to work properly. I have found this method to be the most effective solution. Another approach is to define your property in the following way:

Object.defineProperty(app.config.globalProperties, '$t', {
        /* add your definitions here */
      })

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

Exploring the use of two different array types in the useState hook with TypeScript

Working on a movie gallery project, I am utilizing an API to download movies and TV series. They are then displayed in a Row component where users can click on thumbnails to open them. The challenge arises with TypeScript, as the useState array can receiv ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Storybook is pulling fonts from an incorrect location on the server

Regrettably, I am facing an issue where the fonts do not load when accessing a page with Quasar integration. In the Developer Tools, it shows a path error like this: http://localhost:6006/undefined/node_modules/@quasar/extras/roboto-font/web-font/KFOmCnqEu ...

Find all objects in an array that have a date property greater than today's date and return them

I have an array of objects with a property called createdDate stored as a string. I need to filter out all objects where the createdDate is greater than or equal to today's date. How can this be achieved in typescript/javascript? notMyScrims: Sc ...

VueJS Custom Component Import Functionality Occasionally Succeeds

I am encountering an issue with my VueJS component, Image, being imported into two separate components, A and B. While Image functions correctly in A, it encounters errors in B initially prompting a did you register the component? error in the JS console. ...

I am looking for guidance on the proper way to import MatDrawer and MatDrawerContainer in the app.module.ts file for an Angular

When attempting to implement a side nav using angular material and clicking on the toolbar icon, everything was functioning correctly until I encountered an error while trying to open the navbar: The error message displayed: Unexpected directive 'Ma ...

Is Angular 9's default support for optional chaining in Internet Explorer possible without the need for polyfill (core-js) modifications with Typescript 3.8.3?

We are in the process of upgrading our system to angular 9.1.1, which now includes Typescript 3.8.3. The @angular-devkit/[email protected] utilizing [email protected]. We are interested in implementing the optional chaining feature in Typescript ...

Discovering a DOM Element Post Mouse Click Event Using HostListener in Angular 8

Is there a way to locate the current DOM element on a page after clicking the mouse? I am currently attempting to utilize HostListener in Angular 8. @HostListener('click') onClick(){ window.alert('Current DOM element is'); } ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

How to specify the return type of a promise from an observer in Angular 6

Typically, I prefer using observables. However, in order to avoid 'callback hell' in this particular scenario, I decided to use toPromise(). Unfortunately, I encountered a lint error message when trying to define the return type: The 'Obj ...

Guide on utilizing the useContext hook in React/Next.js while incorporating TypeScript

As I embark on my journey in the world of TypeScript, I find myself working on a new project in Next.js using TypeScript. My goal is to incorporate authentication functionality into this project by utilizing createContext. Coming from a background in JavaS ...

Enable the normal back button functionality when new query parameters are added dynamically

Whenever a page is visited without any parameters, I push some parameters to the Nuxt router. This process can be seen in more detail at https://router.vuejs.org/guide/essentials/navigation.html. For example, if someone visits: /program, they will end up ...

Attempting to access the $ref property in Vue results in an undefined value

When I try to work with $refs in Vue, I keep getting undefined. <div ref="table-ref">This is a sample reference element</div> In my Vue method, I attempt to access the ref and apply a scroll to it const tableRef = this.$refs['ta ...

Troubleshooting CORS, OPTIONS, and PreFlight issues when using Axios to consume a REST API in a Vue.js project

Currently, I am working on developing the front end for a PHP-based application that utilizes a custom management tool. My approach involves using Vue.js to construct the front end and specifically employing Axios to make API calls. I have set up a Lights ...

handling axios retries in main.js within a Vue.js application

I have a method called getUsers within the created hook of the Users Component. Additionally, I have both an access token and refresh token stored in my local storage. What I aim to achieve is that when my access token expires, I can use the refresh token ...

I'm attempting to retrieve mlab data in the console using node.js, but unfortunately encountering an error

I came across this helpful YouTube tutorial:https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s. I followed the steps outlined in the video and made necessary code adjustments based on current updates found through a Google search (to resolve errors enc ...

A guide on navigating to a different component in Vuejs using a link

<div class="enterprise-details" style="margin-top: 20px"> Already signed up? <a href="#"> LOGIN</a></div> <!-- Component for redirection --> <b-button v-if="!registeredUser" class="button-self" v-b-modal.modal-x>Lo ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Why aren't enums that can be derived supported?

Is there a way to create an enum that is a subset of another enum? Sometimes it would be useful to have an enum that is a subset of another Enum with the same values at run time but under a different name. Are there better ways to handle this scenario? ...