Exploring the power of Vue i18n for prop translations in Vue applications

My goal is to translate the titles passed to my component through props. However, it seems that these strings are not being translated like the rest of my code due to being passed as props. Below are the two components I am currently working with:

Parent Component:

<setting-section
    :title="$t('Random Text 1')"
    :description="$t('Random Text 2')"
  >

In the Child:

<template>
  <div class="flex grid w-full">
    <div class="divider mr-4 mt-5" />
    <div class="header col-2">
      <div class="title text-primary">{{ title }}</div>
      <div class="description text-xs">{{ description }}</div>
    </div>
    <div class="flex col-10" v-if="!isLoading">
      <slot />
    </div>
    <div class="flex col-10" v-else>
      <Skeleton height="5rem" />
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Menu',
    props: {
      title: {
        type: String,
        default: '',
      },
      description: {
        type: String,
        default: '',
      },
    },
  };
</script>

However, attempting to use the below variation obviously will not work.

<template>
  <div class="flex grid w-full">
    <div class="header col-2">
      <div class="title text-primary">{{ $t('title')}} </div>
      <div class="description text-xs">{{ description }}</div>
    </div>
  </div>
</template>

Answer №1

Both of your solutions should function properly since we have set up VueI18n at a global level. This means that translation literals can always be accessed from any nested component.

Here is a live demonstration showcasing both use cases :

Vue.component('child-one', {
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>'
});

Vue.component('child-two', {
  template: `<p>{{ $t('message') }}</p>`
});

Vue.use(VueI18n);

const i18n = new VueI18n({
  locale: 'ja',
  fallbackLocale: 'en',
  messages: {
    "ja": {
      "message": "こんにちは、世界"
    },
    "en": {
      "message": "Hello World"
    }
  }
});

new Vue({
  el: "#app",
  i18n,
  data() {
    return {
      locale: "ja"
    }
  },
  watch: {
    locale(newLocale) {
      this.$i18n.locale = newLocale;
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-i18n@[email protected]/dist/vue-i18n.min.js"></script>
<main id="app">
  <div>
    <label><input type="radio" value="ja" v-model="locale" />Japanese</label>
    <label><input type="radio" value="en" v-model="locale" />English</label>
  </div>

  <h3>Passing translated string from parent</h3>
  <child-one :childmsg="$t('message')"></child-one>
  
  <h3>Translations take place in the child component itself</h3>
  <child-two></child-two>
</main>

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

Distinct "namespaces" within HTML

Recently, I've encountered an issue with my application that is causing ID collisions. The application uses AJAX to dynamically load code snippets based on user demand. Although these snippets vary significantly, there are instances where a code snipp ...

Retrieve the parent node and its corresponding children nodes using Vuetify's Tree-view component

Whenever I attempt to choose a node in the Vuetify tree-view while in leaf mode, only the leaf nodes are showing up in the v-model. Is there a way to include all the child nodes along with the selected parent node? Vuetify Version: 2.2.18 Link to the cod ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

Issue: Attempting to write data after reaching the end in Node.js while using

I have encountered the following error: Heading Caught exception: Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (/home/projectfolder/node_modules/express/node_modules/connect/lib/mid ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

utilize a Vue animation complete callback to incorporate a function

Can a function be passed inside the "done" callback for Vue animation? enter: function(e, done) { element.animate({ // ... }, duration, done) } Is there a way to ensure that the next "afterEnter" hook will still be called? If I wer ...

Mean Stack involves the interaction between the client controller and the server controller using routes to communicate and call server methods

I am currently developing a mean stack application and encountering difficulties when attempting to send requests to the Express/Node server in order to delete an element from an array in Mongo. Below is my schema for reference: var DeckSchema = new Schem ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

What sets apart route.use(), route.all(), and route.route() in Express?

Is it possible to replace router.all() with router.use() if the former just matches all methods? Also, what are the differences between using router.use() and router.route()? ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...

How about, "Enhance your website navigation with a sleek anchor

After many attempts to implement smooth scrolling on my Bootstrap project, I have tried numerous Youtube tutorials and Google search results without any success. The latest attempt I made was following this Stack Overflow post Smooth scrolling when clickin ...

Retrieving information from MongoDB within a Vue application using the MEVN stack

I am currently working on developing a full-stack Web Application and I have encountered some frustrating errors while fetching data in the .vue File. My code for fetching data looks like this: <script> import { createHydrationRenderer } from 'v ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...

Creating a selection area with CSS that appears transparent is a straightforward process

I'm currently exploring ways to implement a UI effect on a webpage that involves highlighting a specific area while covering the rest of the page with a semi-transparent black overlay, all using CSS only. What is the most common approach to achieving ...

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

I need to see the image named tree.png

Could someone assist me in identifying the issue with this code that only displays the same image, tree.png, three times? var bankImages = ["troyano", "backup", "tree"]; jQuery.each( bankImages, function( i, val ) { $('#imagesCon ...