先在项目安装 npm install vue-i18n
在根目录新建common/locales/zh.js和common/locales/en.js
//zh.js
export default {
login: {
title:'登录',
register: '注册'
}
}
//en.js
export default {
login: {
title:'Login',
register: 'Register'
}
}
在main.js引入
// 引入并使用vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 引入语言包,注意路径
import Chinese from '@/common/locales/zh.js'; //简体中文
import English from '@/common/locales/en.js'; //英文
// 构造i18n对象
const i18n = new VueI18n({
// 默认语言,这里的local属性,对应message中的cn、en属性
locale: uni.getStorageSync('locale') || 'zh_CN',
// 引入语言文件
messages: {
// 这里的属性名是任意的,您也可以把zh设置为cn等,只是后续切换语言时
// 要标识这里的语言属性,如:this.$i18n.locale = zh|en|cn|xxx
'zh_CN': Chinese,
'en_US': English
}
})
Vue.use(uView);
const app = new Vue({
i18n,
...App
})
页面使用index.vue
<view>
//登录
<view>{{$t('login.title')}}</view>
//注册
<view>{{$t('login.register')}}</view>
//语言选择
<view v-for="(item, index) in lans" :key="index" @click="onLans(index)">
{{ item.name }}
</view>
</view>
data(){
lans: [{
name: '中文'
},
{
name: 'English'
}
]
},
onShow(){
if (uni.getStorageSync('locale') == 'en_US') {
this.$i18n.locale = 'en_US';
} else {
this.$i18n.locale = 'zh_CN';
}
},
methods: {
//切换语言事件
inLans(index ){
if (index == 0) {
this.$i18n.locale = 'zh_CN';
uni.setStorageSync('locale', 'zh_CN');
} else if (index == 1) {
this.$i18n.locale = 'en_US';
uni.setStorageSync('locale', 'en_US');
}
}
}