相关文章推荐
export const SUPPORT_LOCALES = [ ' pt ' , ' en ' , ' es ' ]; export function setI18nLanguage ( locale ) { loadLocaleMessages ( locale ); if ( i18n . mode === ' legacy ' ) { i18n . global . locale = locale ; } else { i18n . global . locale . value = locale ; document . querySelector ( ' html ' ). setAttribute ( ' lang ' , locale ); localStorage . setItem ( ' lang ' , locale ); export async function loadLocaleMessages ( locale ) { // load locale messages with dynamic import const messages = await import ( /* webpackChunkName: "locale-[request]" */ `./locales/ ${ locale } .json` // set locale and locale message i18n . global . setLocaleMessage ( locale , messages . default ); return nextTick (); export default function setupI18n () { if ( ! i18n ) { let locale = localStorage . getItem ( ' lang ' ) || ' pt ' ; i18n = createI18n ({ globalInjection : true , legacy : false , locale : locale , fallbackLocale : ' pt ' setI18nLanguage ( locale ); return i18n ; Enter fullscreen mode Exit fullscreen mode

In src folder do you need create this folder with name locales and in locales folder you create all json file with name example en.json or pt.json or es.json with your translate file ocurrences follow this example json below

name file: locales/en.json
"languages" : { "pt" : "Portuguese" , "en" : "English" , "es" : "Spanish" "title" : { "config" : "Configuration" Enter fullscreen mode Exit fullscreen mode

Now do you need usage translate in component and create this a select or a button for changing language of locale with hook global useI18n

A example basic use in component with a select change of language

<script setup>
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { SUPPORT_LOCALES as supportLocales, setI18nLanguage } from '../i18n';
const { locale } = useI18n({ useScope: 'global' });
watch(locale, (val) => {
  setI18nLanguage(val);
</script>
<template>
  <h1>{{ $t('title.config') }}</h1>
  <select class="App-language" v-model="locale">
    <option
      v-for="optionLocale in supportLocales"
      :key="`locale-${optionLocale}`"
      :value="optionLocale">{{ optionLocale }}
    </option>
  </select>
</template>
    Enter fullscreen mode
    Exit fullscreen mode
    Front-end Developer and Designer specialist in creating technological solutions with Web standards
Always developing solutions with technologies: CSS, HTML, JavaScript, React, Angular, Vue.js
    Front-end Developer and Designer specialist in creating technological solutions with Web standards
Always developing solutions with technologies: CSS, HTML, JavaScript, React, Angular, Vue.js
      

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.

 
推荐文章