1. Installation
Three ways:
1. Script introduction
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
2. npm installation
npm install vue-i18n
3. yarn installation
yarn add vue-i18n
Two, configuration
main.js file configuration
1. Introduce the i18n internationalization plug-in
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
2. Register the i18n instance and import language files, file formats, etc. to analyze
const i18n = new VueI18n({
locale: 'zh', // 定义默认语言为中文
messages: {
'zh': require('@/assets/languages/zh.json'),
'en': require('@/assets/languages/en.json')
}
});
3. Inject i18n into the vue instance
new Vue({
el: '#app',
router,
i18n,
components: { App},
template: '<App/>'
});
4. File format (json file)
First look at the zh.json file, as follows:
The corresponding en.json format is the same as zh.json, just change Chinese to English, as follows:
3. Template rendering
html files need to add {
{}}
{
{$t('common.home')}}
js file
$t('common.home')
Click to switch languages, as follows:
(Note: github address: Avery_G)