1.如果没有package.json则需要创建一个package.json文件,并添加代码
{
"dependencies": {}
}
2.运行 npm install vue-i18n --save
3.在根目录下添加语言包文件
json文件格式
{
"search": "搜索",
"place_order": "下单",
"history": "历史",
"order_list": "订单",
"more": "更多","index":{
"place_order": "下单",
"history": "历史",
"order_list": "订单",
}}
4.index.js声明语言包的别名(别名决定切换的文字,有些小伙伴切换不了的问题就在这)
import zh from './zh'
import en from './en'
import ja from './ja'export default {
'en': en, // 'en'随便立命成什么都可以,但是注意切换的时候是要调用这个'en'的
'zh': zh,
'ja': ja
}
5.在main.js声明全局应用
import VueI18n from 'vue-i18n' //引入npm下载模块
import messages from 'lang/index.js'; //引入自定义语言文件
Vue.use(VueI18n); //全局使用
const i18n = new VueI18n({// 默认选择的语言,防止手动(物理)刷新后回到默认值
locale: uni.getStorageSync('locale') || 'en',
messages: messages
});Vue.prototype._i18n = i18n; //作为属性挂载
const app = new Vue({
i18n,
...App
})
6.使用语言包
<template>
<view>
<view> {{$t('search')}} {{cs}}</view>
<button @click="lang()">切换语言</button>
</view>
</template>
<script>
export default {
data() {
return {
cs: 1,
}
},methods: {
lang() {
if (this.cs == 1) {//刷新赋值语言,'en'一定要是index.js里面立命的
this.$i18n.locale = 'en';//保存到缓存中,防止手动(物理)刷新后语言又回到默认值
uni.setStorageSync('locale', 'en');
this.cs = 0;
} else {
this.$i18n.locale = 'zh';
uni.setStorageSync('locale', 'zh');
this.cs = 1;
}console.log(uni.getStorageSync('locale'))
},}
}
</script>