Utilizing vue-i18n within Class-based Components in Vue 3

Currently, I am in the process of migrating from vue2 to vue3 and using the "Class Style Component".

I have been utilizing vue-i18n. Will I be able to continue using vue-i18n with Vue3?

Here is a snippet from my package.json:

  "dependencies": {

    "vue": "^3.3.4",
    "vue-class-component": "^8.0.0-0",
    "vue-i18n": "^9.5.0",
    "vue-property-decorator": "^10.0.0-rc.3",

Upon inspecting the browser console, I encountered the following error:

Uncaught SyntaxError: Must be called at the top of a `setup` function
    at createCompileError (message-compiler.esm-browser.js:99:19)
    at createI18nError (vue-i18n.mjs:101:12)
    at useI18n (vue-i18n.mjs:2294:15)
    at TestXXXXXX.vue:20:9

The error message indicates that it must be called at the top of a setup function. My question is, can we incorporate the "setup function" in a Class Style Component?

Below is an example of my code structure:

<script lang="ts">

import { useI18n } from 'vue-i18n';

@Component({
  i18n: useI18n()
})
export default class TestXXXXXX extends Vue {
:

If anyone could provide assistance, I would greatly appreciate it. Thank you in advance.

Answer №1

Even though I mentioned it in a previous comment, you can still integrate vue-i18n with vue-class-component. In Vue3, you need to use useI18n at the beginning of a setup function as indicated in your error message. The vue-class-component exports a setup function that can be utilized in various ways, and we will demonstrate how to do so.

To start, you must create your app and install vue-i18n:

In your main.ts file or wherever your app starts:

import { createApp } from "vue";
import App from "./App.vue";
import { createI18n } from "vue-i18n";

const i18n = createI18n({
  locale: "en",
  legacy: false,
  messages: { // add your messages here
    en: {
      common: {
        message: "Hello world!",
      },
    },
  },
});

createApp(App).use(i18n).mount("#app");

You can now utilize $t and useI18n in your project. Here is how to proceed:

In your App.vue file:

<template>
  <HelloWorld msg="common.message"/> <!-- The translation key -->
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import HelloWorld from './components/HelloWorld.vue';

@Options({
  components: {
    HelloWorld,
  },
})
export default class App extends Vue {}
</script>

Lastly, in the HelloWorld.vue component, here are two methods to use it:

<template>
  <div>
    <h1>{{ $t(msg) }}</h1>
    <h2>{{ i18n.t('common.message') }}</h2>
  </div>
</template>

<script lang="ts">
import { Options, Vue, setup } from 'vue-class-component';
import { useI18n } from 'vue-i18n'

@Options({
  props: {
    msg: String
  }
})
export default class HelloWorld extends Vue {
  msg!: string      

  i18n = setup(() => {
    return useI18n()
  })
}
</script>

I would advise against using vue-class-component and recommend utilizing composition API with Vue3 and Typescript instead.

Regardless, I hope this information proves helpful :)

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

Ways to retrieve the mapState property within a method

Is there a way to access the count property within the method while working with vuex? Take a look at my code provided below: Screenshot of Code: https://i.stack.imgur.com/xNUHM.png Error Message [Vue warn]: Computed property "count" was assigned to bu ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> ...

What is the best way to retrieve promiseValue from the response array?

I've run into some challenges while using Promise.all() for the first time with two get-methods. When I check the response in my console log, I can see the data I'm trying to fetch under promiseValue. However, I'm unsure of how to access it. ...

Tips for ensuring equal height and width for a card using the <v-flex auto> component

I am in the process of organizing a set of cards, all of which need to be the same size. Check out an example I have created here: https://codepen.io/creativiousa/pen/BErpPb I attempted to modify my code using <v-card height='100%'> </ ...

Only displaying sub items upon clicking the parent item in VueJS

I'm in the process of designing a navigation sidebar with main items and corresponding sub-items. I want the sub-item to be visible only when its parent item is clicked, and when a sub-item is clicked, I aim for it to stand out with a different color. ...

Are there alternative methods for anchoring an element in Vuetify aside from using the v-toolbar component?

I have been working on positioning certain elements in the app and I have found a method that seems to work, using code like this: <v-toolbar fixed></v-toolbar> Another option is something along these lines: <v-toolbar app></v-toolb ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Integrating Vue Router with a CFML (Lucee) server

I have a Vue Router set up that is working flawlessly for navigation using <router-link to="/test">test</router-link>, but when I manually type the URL into the browser like , it reloads the page and shows a 404 error. On the server-side, I ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Ways to establish unchanging data based on a prop that has the potential to be modified

I am currently working on a demo project that is similar to a Todo-List, and I am facing a challenge with the implementation. Here is an excerpt of the code: Parent.vue <template> <li v-show="currentTab === 1"> <child key="1" :items="p ...

Vue js and axios make it easy to upload multiple files at once

I am encountering an issue where I am attempting to upload multiple images using vuejs and axios, but the server side is receiving an empty object. Despite adding multipart/form-data in the header, the object remains empty. submitFiles() { /* In ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

What is the best method for exchanging data between two Vue instances?

index.html <script defer src='main.js'></script> <script defer src='extension.js'></script> <div id='main-app'></div> <div id='extension'></div> main.js const store ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

Unable to clear computed array property in Vue

Hello there! I am trying to modify a Vue computed array within a watch function, but unfortunately it is not getting emptied before pushing new values. The push operation works fine, however the truncation seems to be ineffective. Do you have any insight ...

Exploring Vue 3 through the lens of class components

Currently, our project is utilizing Vue 2.x and our components are structured as follows: @Component({ template: ` <div> some code .... <div> ` }) export default class class1 extends Vue { @Prop() data: IsomeData; } Vue-class ...