Part One: Preparation
First, we need to create a basic Vue 3 app. If you are not familiar with Vue 3, don't worry, we'll start from scratch.
Open your command line tool and execute the following command:
vue create i18n-app
This will create a new Vue 3 app called “i18n-app”.
After the installation is complete, enter the application directory and start the development server:
cd i18n-app npm run serve
Now, open your favorite code editor and navigate tosrc
In the directorydocument.
We will configure our i18n here.
Part 2: Install and configure i18n
existIn the file, we first need to install the i18n library. Run the following command to install:
npm install vue-i18n@next
After the installation is complete, we need to import and configure i18n.
existIn the file, add the following code:
import { createApp } from 'vue'; import { createI18n } from 'vue-i18n'; import App from './'; const i18n = createI18n({ locale: 'en', // The default language is English messages: { en: { welcome: 'Welcome to my blog!', about: 'About', contact: 'Contact', // More English texts... }, zh: { welcome: 'Welcome to my blog! ', about: 'about', contact: 'connect', // More Chinese text... }, // More languages... }, }); createApp(App).use(i18n).mount('#app');
In the above code, we create ai18n
instance, and configured with the default language to English ('en').
We then define text messages in different languages.
You can add more languages and corresponding text as needed.
Part 3: Using multilingual in components
Now that we have configured i18n, let's use multilingual text in the component.
OpenFile and modify it to the following:
<template> <div> <h1>{{ $t('welcome') }}</h1> <nav> <ul> <li>{{ $t('about') }}</li> <li>{{ $t('contact') }}</li> </ul> </nav> </div> </template> <script> export default { // Component logic...}; </script>
In the above code, we use$t
Method to access text messages in i18n instance.
For example,$t('welcome')
A welcome message under the currently selected language will be displayed.
Part 4: Switch languages
Finally, let’s implement the function of switching languages.
existIn the file, we add a simple button to switch languages.
Revisetemplate
The parts are as follows:
<template> <div> <h1>{{ $t('welcome') }}</h1> <nav> <ul> <li>{{ $t('about') }}</li> <li>{{ $t('contact') }}</li> </ul> </nav> <button @click="toggleLanguage">Switch language</button> </div> </template>
Then, inscript
Partially add the following code:
<script> export default { methods: { toggleLanguage() { const currentLocale = this.$; const newLocale = currentLocale === 'en' ? 'zh' : 'en'; this.$ = newLocale; }, }, }; </script>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.