Vue I18n官网 :Vue I18n
npm install vue-i18n --save
说明:直接下载最新版本的时候,出现了一个报错,后来换回了低一点的版本(如:8.22.1版本),就没出现把报错了,具体的报错如下:
Uncaught TypeError: Cannot read properties of undefined (reading ‘install‘) 页面一片空白
(具体原因目前还没排查处理,如果大家有解决方案,欢迎评论留言~)
在src文件夹下,新建plugins文件夹,里边有两个语言文件包:en.json(英文语言包) 、zh.json(中文语言包)目录如图:
en.json文件:
{"login": {"loginBtn": "LOGIN","loginTitle": "User Login","userName": "Please enter username!","password": "Please enter password!"}
}
zh.json文件:
{"login": {"loginBtn": "登录","loginTitle": "用户登录","userName": "请输入用户名","password": "请输入密码"}
}
i18n.js文件:
import Vue from 'vue'
import VueI18n from 'vue-i18n'Vue.use(VueI18n)function loadLocaleMessages() {const locales = require.context('./lang', true, /[A-Za-z0-9-_,\s]+\.json$/i) // 在vue项目中使用require.context()引入某个文件夹下所有文件console.log('locales:', locales)const messages = {}locales.keys().forEach(key => {const matched = key.match(/([A-Za-z0-9-_]+)\./i)if (matched && matched.length > 1) {const locale = matched[1]messages[locale] = locales(key)}})return messages
}export default new VueI18n({locale: process.env.VUE_APP_I18N_LOCALE || 'zh', // 设置页面的默认语言fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'zh',messages: loadLocaleMessages()
})
此外,还要在vue.config.js文件中,配置以下内容:
pluginOptions: {i18n: {locale: 'en',fallbackLocale: 'en',localeDir: 'i18n',enableInSFC: true}},
main.js文件引入i18n
import i18n from './plugins/i18n/i18n.js' // 使用i18n实现国际化
console.log('i18n:', i18n)
i18n.locale = 'zh' // 初始化i18n,默认英文显示new Vue({router,store,i18n,render: h => h(App)
}).$mount('#baseApp')
3、使用:
{{ $t('login.loginBtn') }}
4、注意:语言包文件的数据持久化。