uni-app项目使用多语言切换功能

1.下载安装(vue-i18n模块)

npm install vue-i18n --save

2.如果项目中没有package.json文件,在根目录下新建package.json文件,并把以下代码加入:

{
    "dependencies": {
        "vue-i18n": "^8.27.0"
    }
}

从新执行安装命令:npm install vue-i18n --save

3.根目录下新建lang文件夹以及添加语言包en.json和zh.json,可自行添加其他语言包(看自己需求)还有语言配置文件index.js 如图所示:

4.配置lang文件夹下的index如下:

import zh from './zh'
import en from './en'
 
export default {
	'en':en,
	'zh':zh
}

5.配置用到的语言json文件:举例如下:(特别注意json之间数据结构是一致的)

en.json文件如下:

{
	"index":{
		"hometitle":"Information",
		"ceshi":"demo"
	},
	"tabbar":{
		"search":"search",
		"place_order":"place order",
		"history":"history",
		"order_list":"order",
		"more":"more"
	}
}

zh文件如下:

{
	"index":{
		"hometitle":"标题信息",
		"ceshi":"测试"
	},
	"tabbar":{
		"search":"搜索",
		"place_order":"下单",
		"history":"历史",
		"order_list":"订单",
		"more":"更多"
	}
}

6.配置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-US',  // 默认选择的语言
  messages 
});
 
 
Vue.prototype._i18n = i18n;   //作为属性挂载
 
 
const app = new Vue({
	i18n,
    ...App
})

7.直接引入使用{{$t('tabbar.search')}}

<view class="pub_bar_img" @click="gototabbar('/pages/index/index')">
	<view :class="[selectnum==1?'tabbar_taxt':'img_boot_box']">        
        {{$t('tabbar.search')}}
    </view>
</view>

8.  语言切换功能,在设置的页面直接使用内存uni.setStorageSync('locale', this.locale);this.locale是自己需要设置的语言 

posted @ 2022-10-20 22:19  土小狗  阅读(801)  评论(0编辑  收藏  举报