uniapp国际化配置

1、创建资源文件

创建一个locale文件夹,新增index.js,en.json,zh-hans.json
在这里插入图片描述

2.配置locale文件夹中的index.js文件

import Vue from 'vue'
import VueI18n from 'vue-i18n'// v8.x
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
import ja from './ja.json'


Vue.use(VueI18n)
const messages = {
	en,
	'zh-Hans': zhHans,
	'zh-Hant': zhHant,
	ja
}

let i18nConfig = {
  locale: uni.getLocale(),// 获取已设置的语言
  messages
}
const i18n = new VueI18n(i18nConfig)
export default i18n

3、main.js 引入

// VUE2
import i18n from './locale'

Vue.use(i18n)

const app = new Vue({
	i18n,
  ...App
})

4、国际化json文件内容

{
  "index.title": "Hello i18n"
}

5、页面使用i18n

vue和js里的内容国际化是与web通行的方案。

<template>
  <view class="container">
    <view class="title">{{$t('index.title')}}</view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
      }
    }
  }
</script>

//普通文本使用方式: 
{{ $t('index.titlee') }}
//标签内使用方式:   
:placeholder="$t('index.title')"
//js内使用方式       
this.$t('index.title')

6、在js文件中使用国际化

import i18n from '../locale'

export default {
  '401': i18n.t('errorCode.401'),
  '403': i18n.t('errorCode.403'),
  '404': i18n.t('errorCode.404'),
  'default': i18n.t('errorCode.default')
}
// 即在引入后使用
i18n.t('')

7、与后台同步切换语言文件

利用封装的request.js对发给后台的接口Header进行统一处理

import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import i18n from '../locale'
let timeout = 60000
const baseUrl = config.baseUrl

const request = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  config.header["Accept-Language"] = (uni.getLocale()==='zh-Hans'?'zh':'en') || "en"
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
    uni.request({
        method: config.method || 'get',
        timeout: config.timeout ||  timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      }).then(response => {
        let [error, res] = response
        if (error) {
          toast(i18n.t('request.unusual'))
          reject(i18n.t('request.unusual'))
          return
        }
        const code = res.data.code || 200
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        if (code === 401) {
          showConfirm(i18n.t('request.exceedTheTimeLimit')).then(res => {
            if (res.confirm) {
              store.dispatch('LogOut').then(res => {
                uni.reLaunch({ url: '/pages/login' })
              })
            }
          })
          reject(i18n.t('request.ofNoAvail'))
        } else if (code === 500) {
          toast(msg)
          reject('500')
        } else if (code !== 200) {
          toast(msg)
          reject(code)
        }
        resolve(res.data)
      })
      .catch(error => {
        let { message } = error
        if (message === 'Network Error') {
          message = i18n.t('request.unusual')
        } else if (message.includes('timeout')) {
          message = i18n.t('request.overtime')
        } else if (message.includes('Request failed with status code')) {
          message = i18n.t('request.system') + message.substr(message.length - 3) + i18n.t('request.unusual2')
        }
        toast(message)
        reject(error)
      })
  })
}

export default request

即将选择语言写到接口的Header中,实现与后端同步切换语言

config.header["Accept-Language"] = (uni.getLocale()==='zh-Hans'?'zh':'en') || "en"

8、在页面切换语言

注意:页面中设置语言后需要调用 this.$i18n.locale = ‘zh-Hans’ 后生效

<template>
	<view>
		<view class="login-footer">
			<text @click="changeLang('en')" style="margin-right: 5px;" :class="lang==='en'?'text-black':'text-blue'">English</text>
			<text @click="changeLang('zh')" style="margin-left: 5px;" :class="lang==='en'?'text-blue':'text-black'">中文</text>
		</view>
	</view>
</template>
<script>
export default {
		data() {
			return {
			// 语言标识
				lang:''
			}
		},
		methods: {
		// 动态更改语言
			changeLang(e) {
				this.lang = e || 'en'
				console.log(e);
				if (e === 'en') {
					uni.setLocale('en');
					this.$i18n.locale = 'en'
					this.changTitle()
				} else {
					uni.setLocale('zh-Hans');
					this.$i18n.locale = 'zh-Hans'
					this.changTitle()
					this.lang = 'zh'
				}
			}
		}
	}
</script>

<style lang="scss">	
	.login-footer {
		height: 40px;
		line-height: 40px;
		position: fixed;
		// bottom: 40px;
		margin-top: 20px;
		width: 100%;
		text-align: center;
		font-family: Arial;
		font-size: 18px;
		letter-spacing: 1px;
	}
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
UniApp 提供了国际化的支持,可以方便地将应用程序本地化为不同的语言版本。要在 UniApp 中实现国际化,你可以按照以下步骤进行操作: 1. 在 `src` 目录下创建一个名为 `lang` 的文件夹,用于存放不同语言版本的文件。 2. 在 `lang` 文件夹下创建一个 `locale.json` 文件,用于存放公共的翻译文本。 ```json // locale.json { "en": { "hello": "Hello", "world": "World" }, "zh-CN": { "hello": "你好", "world": "世界" } } ```*** ```json // en.json { "welcome": "Welcome" } // zh-CN.json { "welcome": "欢迎" } ``` 4. 在需要使用翻译文本的面或组件中,使用 `$t` 方法进行翻译。 ```html <template> <view> <text>{{$t('hello')}}</text> <text>{{$t('welcome')}}</text> </view> </template> ``` 5. 配置语言环境,在 `main.js` 中引入 `@dcloudio/uni-i18n` 插件,并设置默认语言和语言列表。 ```javascript import Vue from 'vue' import App from './App' import i18n from './lang' Vue.prototype._i18n = i18n const app = new Vue({ i18n, ...App }) app.$mount() ``` 6. 在 `lang` 文件夹下创建 `index.js` 文件,用于初始化语言环境。 ```javascript // index.js import Vue from 'vue' import uniI18n from '@dcloudio/uni-i18n' Vue.use(uniI18n, { locale: 'zh-CN', fallbackLocale: 'en', messages: { 'en': require('./en.json'), 'zh-CN': require('./zh-CN.json') } }) ``` 以上是在 UniApp 中实现国际化的基本步骤,你可以根据需要扩展和调整。希望对你有所帮助!如果有更多问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wen先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值