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> < /div>
<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>