一、安装
vue-i18n目前版本是8.21.0
三种方式
1、script引入
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
2、npm安装
npm install vue-i18n
3、yarn安装
yarn add vue-i18n
二、配置文件
1.语言文件(json、js)
module.exports = {
"month1": "1月","month2": "2月","month3": "3月","month4": "4月","month5": "5月","month6": "6月","month7": "7月","month8": "8月","month9": "9月","month10": "10月","month11": "11月","month12": "12月"
}
module.exports = {
"month1": "January","month2": "February","month3": "March","month4": "April","month5": "May","month6": "June","month7": "July","month8": "August","month9": "September","month10": "October","month11": "November","month12": "December"
}
main.js
2.引入i18n国际化组件
// 引入国际化
import VueI18n from "vue-i18n";
Vue.use(VueI18n)
3.注册i18n实例并引入语言文件
const i18n = new VueI18n({
locale: window.localStorage.getItem('locale') == null ? "zh" : window.localStorage.getItem('locale'), // 语言标识,默认中文messages: {
'zh': require('./utils/lang/zh'), // 中文语言包'en': require('./utils/lang/en') // 英文语言包//语言可扩充},
})
4.将i18n注入到vue实例中
new Vue({
el: '#app',router,i18n,components: {
App},template: '<App/>'
})
App.vue
<template><div class="page bg"><router-view /></div>
</template><script>
export default {
data() {
return {
};},mounted() {
this.localeLangage();},methods: {
//获取路径参数getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");var r = window.location.href.substr(window.location.href.lastIndexOf("?") + 1).match(reg);if (r != null) return unescape(r[2]);return null;},localeLangage() {
let localeLangage = this.getQueryString("locale");if (localeLangage === "zh") {
this.$i18n.locale = "zh-CN";} else if (localeLangage === "en") {
this.$i18n.locale = "en-US";}localStorage.setItem("locale", this.$i18n.locale);this.GLOBAL.locale = localeLangage;window.locale = this.GLOBAL.locale;}}
};
</script><style scoped lang="scss">
</style>
三、模板渲染
//$route.query.month :1到12<span>{
{
$t('month'+$route.query.month)}}</span>
四、总结
- 语言切换通过改变
this.$i18n.locale
例如下方图片为vantUI国际化的配置this.$i18n.locale='zh-CN'
就是对应的简体中文
- vue-i18n 数据渲染的模板语法
- { {}}
<span>{ {$t('month')}}</span>
- v-text
<span v-text="$t(month')"></span>
- data中
this.$t('month')
- 可以使用引入的UI库自带的国际化功能
- 可能的问题