Home >Web Front-end >Vue.js >How to implement multi-language switching and internationalization in Vue projects

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

王林
王林Original
2023-10-08 13:39:251742browse

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')

}
})

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:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn