Home >Web Front-end >Vue.js >How to implement multi-language switching and internationalization in Vue projects
How to achieve multi-language switching and internationalization in Vue projects
Introduction:
In the current context of globalization, many websites and applications need to provide Multi-language support to meet the needs of different user groups. As a popular front-end framework, Vue also provides a convenient way to achieve multi-language switching and internationalization. This article will introduce how to implement multi-language switching and internationalization in the Vue project, and give specific code examples.
1. Preparation
npm install vue-i18n --save
Taking English as an example, add the following content in en.json:
{
"header": "Welcome to my website!",
"content ": "This is a Vue project for multi-language support.",
"button": "Switch Language"
}
Add the following content in zh.json:
{
"header": "Welcome to my website!",
"content": "This is a project using Vue to implement multi-language support.",
"button": " Switch language"
}
2. Configuration and use
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en', // The default language is English
messages: {
en: require('./locales/en.json'), zh: require('./locales/zh.json')
}
})
new Vue ({
i18n,
render: h => h(App)
}).$mount('#app')
div> <script><br>export default {<br> methods: {</script> } So far, we have completed the configuration and use of multi-language switching and internationalization in the Vue project. In the web page, after the user clicks the switch language button, the language displayed on the page can be switched in real time. Conclusion:
<h1>{{ $t('header') }}</h1>
In order to implement the language switching function, we can add a button to the component and call this.$i18n in the click event .locale method to switch the current language. For example, in the Header.vue component, we can add the following code:
<h1>{{ $t('header') }}</h1>
switchLanguage() {
if (this.$i18n.locale === 'en') {
this.$i18n.locale = 'zh'
} else {
this.$i18n.locale = 'en'
}
}
}
Implementing multi-language switching and internationalization in a Vue project is a relatively simple process. By using the vue-i18n plugin, we can easily introduce multiple language resource files into the project and use the translated text in the component through the this.$t method. At the same time, we can also use this.$i18n.locale method to switch the current language. I hope this article can help readers successfully implement multi-language switching and internationalization functions in Vue projects.
The above is the detailed content of How to implement multi-language switching and internationalization in Vue projects. For more information, please follow other related articles on the PHP Chinese website!