Recently, some people joked about the project after using Vue3, there were a lot of problems, difficult to fill the hole, and even found that some third-party libraries did not release the version of Vue3, so they made a joke, strongly recommend not to use Vue3.

Do technical pre-research and compatibility research before development, especially for new technology or major updates. Unless you have the guts, don’t use it in a formal project without adequate pre-research.

Recently, one of my Vue3 projects is connected to the internationalization configuration. The overall process is not much different from Vue2. I would like to share my technical experience here.

Install the vue – i18n


npm i vue-i18n --save

Copy the code

The name vue-i18n is made up of the first and last letters of the English word and the number of characters in the middle, 18, meaning “internationalization.”

Configuration Locales

Create a new locales folder in the SRC project and a new language folder inside to store the text configuration for each language. Create en and zh-cn folders in language, and create index.js for them, and fill in the following information:


// src/locales/language/zh_CN/index.js

export default {

    title: "Chinese Title",}// src/locales/language/en/index.js

export default {

    title: "English title",}Copy the code

Implement getLangs. Js

Create a new getlangs.js file in the Locales to get the language packs in the Language folder and expose them.

Lodash-es is used here and you need to install it:


npm i lodash-es --save

Copy the code

The specific code is as follows:


import { set } from 'lodash-es'

const modules = import.meta.globEager('./language/**/*.js')

function getLanguages(langs, prefix = 'lang') {

  const obj = {}

  Object.keys(langs).forEach((key) = > {

    const mod = langs[key].default

    let k = key.replace(`. /${prefix}/ `.' ').replace(/ ^ \ \ / /.' ')

    const lastIndex = k.lastIndexOf('. ')

    k = k.substring(0, lastIndex)

    const keyList = k.split('/')

    const lang = keyList.shift()

    const objKey = keyList.join('. ')

    if (lang) {

      set(obj, lang, obj[lang] || {})

      set(obj[lang], objKey, mod)

    }

  })

  return obj

}

const { language } = getLanguages(modules)

export default language
Copy the code

Create an i18N instance

Next, you need to create an i18N instance and mount it to Vue. Create a new i18N.js in the locales. The code is as follows:


import { createI18n } from 'vue-i18n'

import messages from './getLangs'

export default createI18n({

  legacy: false.locale: window.localStorage.getItem("lang") | |'zh_CN',

  messages,

})
Copy the code

You can see that the default language configuration is obtained from localStorage in the browser. If not, the default language configuration is zh-cn. After switching the language, you need to save the current language, otherwise the user will refresh, but back to the default language configuration.

In main.js, introduce:


import i18n from './locales/i18n'

const app = createApp(App)

app.use(I18n).mount("#app")
Copy the code

Used in templates

The function receives the path to the language configuration file and properties, connected by dot syntax. If it cannot be found, the entire function name is displayed as a character.


<template>

<p>{{t(`index.title`)}}</p>

</template>

import { useI18n } from "vue-i18n";

export default {

    setup() {

        const { t } = useI18n();

        return { t }

    }

}

Copy the code

Language switching

There are two common language switching modes. One is to change the current language configuration to the URL. Switching the language is to skip to the corresponding route and then display the corresponding text in the current language.

The second is the no-refresh/jump switchover. The current language is stored in the local cache and the language is switched by changing the value of vue-i18n locale.

The second option is recommended here. Switching languages does not require a page refresh or a jump.


<template>

  <a

    href="javascript:;"

    @click="setLocals(locale === 'zh_CN' ? 'en' : 'zh_CN')"

  >{{ locale === 'zh_CN' ? 'English' : 'middle'}}</a>

</template>

<script>

import { useI18n } from "vue-i18n";

import { ref } from "@vue/reactivity";

export default {

setup() {

    const { t, locale } = useI18n();

    const getLocals = () = > window.localStorage.getItem("lang") || locale.value;

    const currentLocale = ref(getLocals());

    const setLocals = (lang = "") = > {

      locale.value = lang;

      window.localStorage.setItem("lang", lang);

    };

    if (!window.localStorage.getItem("lang")) {

      setLocals(currentLocale.value);

    } else {

      if (currentLocale.value !== locale.value) {

        setLocals(currentLocale.value);

      }

    }

    return{ t, locale, setLocals, }; }};</script>
Copy the code

If the locale is not configured, the default language configuration is obtained. When you change the locale, you need to save the current language to the local cache.

About You need to refresh after switching to take effect

In the example above, the text rendered directly by the t function in the template can be updated without refreshing the view language when the language is switched, but if the t function is used directly in the Setup, the update does not take effect immediately and needs to be refreshed.

It is not recommended to use the T function outside of the template. If necessary, you can define multilingual text in the component and access it in the template as key-value pairs.

Switching languages triggers updates to other components

In some scenarios, the text displayed on the page is obtained externally, and updates cannot be triggered directly by a language switch, requiring a broadcast effect similar to that of a sibling component.

Global Bug has been removed from Vue3 and can be replaced by plug-ins such as Mitt.

Write in the last

Writing is not easy. I hope I can get a “like” from you. If the article is useful to you, you can select “bookmark”. If there are any mistakes or suggestions in the article, please comment on it. Thank you. ❤ ️

Welcome to other articles

  • Actual: Front-end interface request parameter confusion
  • Actual: Implement a Message component with Vue3
  • Actual: Vue3 to implement the Image component, by the way, support lazy loading
  • One Piece, Vue.js 3.0 brings what updates
  • This article digests the major new features of ES7, ES8, and ES9
  • Technical team’s common problems and solutions
  • 10 new features commonly used in ES6
  • Vue3’s Script setup grammar sugar is really cool