Home > Web Front-end > Vue.js > body text

How to implement multi-language switching and internationalization in Vue projects

王林
Release: 2023-10-08 13:39:25
Original
1657 people have browsed it

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

  1. Install the necessary dependencies
    Before we start, we need to install the vue-i18n plug-in to achieve multi-language support. In the project root directory, open the command line tool and execute the following command:

npm install vue-i18n --save

  1. Create language resource file
    In src Create a locales folder under the directory and create JSON files in multiple languages, such as en.json and zh.json. These files will store translation data for different languages.

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

  1. Import and configure vue-i18n
    In the main.js file, we first need to import vue-i18n and configure it. Add the following code at the beginning of the file:

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')
Copy after login

}
})

new Vue ({
i18n,
render: h => h(App)
}).$mount('#app')

  1. Use multiple languages ​​in components
    Next, in components that require multi-language support, we can use this.$t to get the translated text. For example, in the Header.vue component, we can use it like this:

  1. Switch language
    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:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!