How to internationalize the vue3 project
- We have already attributed vue2, using i18n, for internationalization
- So how do we configure i18n for vue3?
Configuration
Ⅰ, installation
npm i vue-i18n
Ⅱ, create il18n
- In the src directory, create the i18n folder and create three files below:
- ① => The main file is used to import i18n and related configurations
- ② => Store Chinese content
- ③ => Store English content
① Example =>
import { createI18n } from 'vue-i18n'; import ZH from './'; import EN from './'; const messages = { zh: { ...ZH }, en: { ...EN }, }; const i18n = createI18n({ legacy: false, globalInjection: true, locale: 'zh', messages }); export default i18n;
The locale attribute is used to set the initial language, and the value must correspond to the attribute key in messages.
② Example =>
export default { person: { name:'Zhang San', hobby:'Singing, rap, basketball' }, };
③ Example =>
export default { person: { name:'zhangsan', hobby:'Singing and dancing, rap, basketball' }, };
Ⅲ, configure i18n in
import { createApp } from "vue"; import App from "./"; import i18n from './i18n/index'; const app = createApp(App); app .use(i18n) .mount("#app");
use
Ⅰ. Use in html. If you are only used in html, you don’t need to import anything.
<template> <div> <span> {{ $t("") }} </span> <span> {{ $t("") }} </span> </div> </template>
Ⅱ. Use in js. You need to obtain it by importing getCurrentInstance.
<script setup> import { getCurrentInstance } from "vue"; const { $t } = getCurrentInstance().proxy; ( $t("") ); // => Get the value</script>
Ⅱ, modify the language (and obtain the current language)
- To switch language, you need to import the locale attribute of vue-i18n. locale is a ref object, and you need to modify the value.
- Do not modify i18n/file, exported object properties
<script setup> import { useI18n } from 'vue-i18n' const { locale } = useI18n() // Switch Chinesefunction changeZh(){ = 'zh'; }; // Switch to Englishfunction changeEn(){ = 'en'; }; </script>
Summarize
This is the end of this article about how to internationalize the vue3 project. For more relevant content on internationalization of vue3 project, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!