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

Create a unique component in ReactJS with the react-google-maps package to enhance your user interface

I would like to integrate a custom marker component into the map, but I have observed that using react-google-maps/api does not support rendering custom components. To illustrate this, here is an example of the code I used: const CustomMarker = ({ text }) ...

Inquiries about utilizing setTimeout with backbone.js and effectively managing timeouts

One of the questions I have is related to clearing timeouts using clearTimeout(content.idTimeout) for a specific idTiemout. But how can I clear all timeouts at once? Here is the model I am working with: var ContentModel = Backbone.Model.extend({ URL: "htt ...

Tips for showcasing images consistently in a V-Card with uniform sizes

Hey there, I'm facing a bit of a challenge that I can't seem to crack. Apologies for not sharing my entire code. So here's the problem: I'm working on this: <v-card> <v-img :src=“{{person.png}}”</v-img> <v-card& ...

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

The Angular component router-outlet is not recognized as a known element

I have encountered an error message: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module. 2. If 'router-outlet' is a Web Component then add ...

Send functions from the back-end Node to the front-end Angular

Introduction I am currently working on a project that involves verifying email addresses within an API in order to grant users access to a restricted section. To accomplish this, I have developed backend node code with three functions built using Node and ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

What is the best way to include a new user in my list of friends within the User schema?

Working on my customized social media platform, I have implemented a feature where users can send friend requests by clicking on a button. <form action="/requests" method="POST"> <input type="hidden" name="send ...

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

Having trouble initiating a "curl:localhost:3000" connection, receiving a URI Error message

Recently delving into the realm of node js, I have embarked on a journey to start up a server and experiment with an app designed to trim URLs. However, I find myself at an impasse. Environment: Windows Text Editor: VSCode Below is my code for index.js ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Choosing an element in JQuery based on the value of its style property

I have three divs with the same class but different styles. I need to select only the third one using JQuery. <div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-div ...

Utilizing local storage functionality within AngularJS

I've been encountering challenges while trying to integrate local storage using ngStorage in my ongoing AngularJS project. Despite fixing what seems to be the root cause of data type problems and errors during debugging, issues persist. Here is the P ...

Anguar server encountered a startup issue and failed to initialize

My server.js file looks like this: var express = require('express'), api = require('./api'), app = express(); app .use(express.static('./public')) .use('./api', api) .get('*', ...

How can I ensure that an item stays in place within a vertically sortable list using Dndkit? (I am also considering alternative drag-and-drop libraries)

Let's say for instance that 5 was marked as frozen. If 4 was then moved below 6, the change in arrangement would be as follows: before: https://i.sstatic.net/iVZFtAmj.png after: https://i.sstatic.net/tCq09Qgy.png My current approach involves us ...