Having trouble with this.$.... not functioning properly post migration from Vue2 to Vue3

Recently, I began the migration process using the migration guide and the Compat build to ensure a smoother transition. Here is how I have configured the vue.config.js:

chainWebpack: (config) => {
// Set alias for Vue compatibility build
config.resolve.alias.set('vue', '@vue/compat');

// Set other aliases
config.resolve.alias
  .set('@common', path.resolve('src/common'))
  .set('@', path.resolve('src/'));

// Add extensions
config.resolve.extensions
  .merge(['.js', '.ts', '.tsx']);

// Modify vue-loader options
config.module
  .rule('vue')
  .use('vue-loader')
  .tap((options) => {
    return {
      ...options,
      compilerOptions: {
        compatConfig: {
          MODE: 2,
        },
      },
    };
  });
 },

I also made changes in my main.ts file:

  createApp({
router,
i18n,
render: () =>
  h(App, {
    logo: '/img/sodra-logo.svg',
  }),
  }).mount('#app');

However, when running npm run serve, I encounter numerous errors that mostly revolve around messages like:

TS2339: Property '$t' does not exist on type 'HomePage'.
311 |       {
312 |         routeName: routeNameHomePage,
> 313 |         name: this.$t('breadcrumbs.' + routeNameHomePage).toString(),
        |                    ^^
    314 |       },
    315 |     ];
    316 |

These errors seem to be related to various instances of this.$, including this.$route and this.$moment. I have researched if there have been any deprecations regarding the use of $ but couldn't find anything conclusive. It appears that some configuration might have been missed.

Here is an excerpt from my tsconfig.json file where a TypeScript error is being thrown:

    {
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "allowJs": true,
    "baseUrl": ".",
    "types": ["vite/client", "vue", "webpack-env", "jest"],
    "paths": {
      "@/*": ["src/*"],
      "@common/*": ["src/common/*"]
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

Answer №1

With the introduction of Vue 3, the use of this.$ syntax has been replaced by a new concept called hooks. Hooks are essentially a set of functions that begin with the prefix use. For instance:

  • this.$router is now useRouter()
  • this.$route is now useRoute()
  • this.$v is now useVuelidate()

In addition, developers have the option to create their own hooks simply by defining a JavaScript function in a file and exporting it.

const bar = new Bar();

function useBar() {
    return bar;
}

export default useBar;

By doing this, you can globally access bar, similar to how this.$bar would have worked if it was available.

Answer №2

With the release of Vue 3, the this.$ syntax has been marked as deprecated. Instead, developers are encouraged to import functions manually on a per-component basis.

For instance, it is now recommended to write code like this:

<script>
import { t } from '@/i18n'

export default defineComponent({
 const returnTranslatedName = computed(() => t('breadcrumbs.path.name')
})
</script>

<template>
 <div>
  {{t('breadcrumbs.path.name'}}
   <!-- OR -->
  {{returnTRanslatedName}}
 </div>
</template>

Please let me know if you find this explanation helpful or if you have any further questions.

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

Troubleshooting tsconfig configuration issue in Visual Studio Code for ExpressJS with TypeScript and Vitest integration testing

Let's dive right in with an illustration: Here is a simplified version of my project structure: src/ app.ts test/ integration/ example.spec.ts tsconfig.json tsconfig.json The main tsconfig.json file includes these settings: { & ...

Unlocking the Power of Mixpanel within Nuxt.js

Is it possible to integrate Mixpanel analytics into Nuxt.js? Although I am new to Nuxt.js, Vue, and Mixpanel, the website I have inherited is performing well so I prefer to learn how to incorporate Mixpanel rather than make drastic changes. Adding Google ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

Navigating to a specific section within a Vue.js child component by scrolling

I am currently working on a functionality where I need to trigger an event from a child component to the parent that will automatically scroll to the correct section based on a reference or ID. For instance, I have a navigation menu as a child component wi ...

a helpful utility type for extracting a union from a constant array of strings

I create string arrays using const assertions and then use them to generate union types. const elements = ["apple", "banana", "orange"] as const; type elementsUnion = typeof elements[number]; // type elementsUnion = "appl ...

Capturing user audio on the client side with Angular

Is there a built-in feature in Angular to record client-side audio input? I have attempted using the p5 library, but it is encountering integration problems. ...

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 ...

Tips for resolving the <!--bindings={ "ng-reflect-ng-for-of": "" }--> bug

Just starting out with Angular and I am having some issues with event binding and property binding in my game-control component. I have a button that, when clicked, adds numbers to an array using setInterval method. I am also passing data between compone ...

Mat backspin dialogue spinner

Our current setup involves using a progress spinner for each API call. The spinner is registered at the app module level, but we are facing an issue where the spinner hides behind the dialog popup. In order to solve this problem, we have decided to includ ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Using Node.js in conjunction with Nuxt.js: a beginner's guide

I have a server.js file located in the "Server" directory, which is connected to Nuxt.js server.js const express = require('express'); const app = express(); app.get('/api/data', (req, res) => { res.json({ message: 'Hello fr ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Harnessing the power of React context alongside React hooks in TypeScript

Here is an example demonstrating my attempt at implementing react's context with react hooks. The goal is to easily access context from any child component using the code snippet below: const {authState, authActions} = useContext(AuthCtx); First, I ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

Pass the validation errors from Laravel controller to Vue component

Hello everyone, I'm in need of assistance with returning error validation for the following code implemented in Vue: Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' =&g ...

What is the best way to convert the link <a href="/main/@{{item.id}}"> to v-bind:href in Vue2.0?

Is there a way to use v-bind:href to splice attributes like href in Vue2? For instance, transforming <a href="/main/@{{item.id}}"> to v-bind:href="/main/@{{item.id}}" ...

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Send all links that have the # symbol in them to a different location

Since switching the Vue router mode from hash to history, it seems that the old links are not correctly redirecting users to the new URL. It appears that some users are still trying to access the site through the old link. const router = new Router({ m ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...