vue/uniapp项目进行国际化(中英文切换)

8 篇文章 1 订阅
1 篇文章 0 订阅

原理

就是先准备好每种语言的数据文件,当选中该语言时,就渲染该语言对应的数据文件

1.安装插件

需要使用 i18n 插件 i18n官方文档

npm 安装

npm install vue-i18n --save

2.准备每种语言的数据文件

注意:这两个文件的数据结构包括对象下的键名(key)都完全一样,只有 value 的值不一样
en.js(英文时需要的数据)

// en.js
export default {
	  index: {  
	    invite: 'Invite',  
	    game: 'Game'  
	  }
}

zh.js(中文时需要的数据)

// zh.js
export default {
	index: {  
	  invite: '邀请',  
	  game: '游戏'  
	}
}

3.在main.js 引入插件和语言文件 并做处理

import Vue from 'vue'
import App from './App'

import ZH from './locales/zh.js'
import EN from './locales/en.js'

import VueI18n from 'vue-i18n'
Vue.use(VueI18n);

const i18n = new VueI18n({  
  locale: 'zh-CN',  //默认选择的语言类型 这里默认中文
	messages: {
		'zh-CN': ZH,
		'en': EN
	}
})

Vue.prototype._i18n = i18n

Vue.config.productionTip = false

App.mpType = 'app'

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

4.在页面渲染数据

我是在uniapp项目中演示的

<template>  
  <view class="uni-content"> 
  	<view>{{ this.$t('index.invite') }}</view>  
    <view>{{ this.$t('index.game') }}</view>   
    <view>{{ index.invite }}</view>  
    <view>{{ index.game }}</view>  
		<view class="" @click="change">
			切换
		</view>
  </view>  
</template>  

<script>  
export default {  
  computed: {  
  // 通过 this.$t('index') 获取之前第二步语言数据文件下的 index 对象
    index () {  
      return this.$t('index')  
    }  
  },
	methods: {
		change () {
			console.log(0)
			if(this._i18n.locale == 'zh-CN') {
				this._i18n.locale = 'en'
				return
			}
			else if(this._i18n.locale == 'en') {
				this._i18n.locale = 'zh-CN'
				return
			};
			
		}
	}
}  
</script>  

<style>  
</style>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值