中英文切换(也可以多个)
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、hbuilderx终端运行命令
示例:npm install vue-i18n --save
二、创建目录lang下面的en.js和zh.js
1.en.js(在里面写上自己所需要的参数)
1.zh.js(在里面写上自己所需要的参数)
2.在main.js导入
代码如下(示例):
import Vue from 'vue'
import App from './App'
//语言
import VueI18n from 'vue-i18n'; //引入npm下载模块
import en from './lang/en.js'; //引入自定义语言文件
import zh from './lang/zh.js''
Vue.config.productionTip = false
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: uni.getStorageSync('locale') || 'zh', // 默认选择的语言
messages:{
zh,en
}
});
Vue.prototype._i18n = i18n;
const app = new Vue({
i18n,
...App
})
app.$mount()
2.页面展示
代码如下(示例):
<template>
<view class="content">
<view class="pub_bar_img" @click="gototabbar('/pages/index/index')">
<view> {{$t('index.func.jc')}}</view>
</view>
<!-- <button @click="langChange">切换语言</button> -->
<view style="width: 100%;height: 60px;background-color: aquamarine;">
<view @click="langChange(item)" v-for="(item,index) in list"
style="height: 30px;margin-top: 10px; line-height: 30px;background-color: pink;">
{{item.name}}
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [{
id: 2,
name: '中文',
lang: 'zh'
},
{
id: 2,
name: 'ENGLISH',
lang: 'en'
}
]
}
},
methods: {
langChange(item) {
if (item.id == 1) {
this._i18n.locale = item.lang
this.setTitle()
} else {
this._i18n.locale = item.lang
this.setTitle()
}
uni.setStorageSync('locale', this._i18n.locale)
},
setTitle() {
//修改tabbar
uni.setTabBarItem({
index: 0,
text: this.$t('index.tab.tabbar1')
}),
uni.setTabBarItem({
index: 1,
text: this.$t('index.tab.tabbar2')
}),
uni.setTabBarItem({
index: 2,
text: this.$t('index.tab.tabbar3')
}),
uni.setTabBarItem({
index: 3,
text: this.$t('index.tab.tabbar4')
})
},
}
}
</script>
<style>
.content {
text-align: center;
}
</style>
修改导航栏
onShow() {
uni.setNavigationBarTitle({ // 修改头部标题(在每个页面写,我是这样的,也可以和tabber写一块,但是我写的不生效,所以就选择了在每个页面写就生效了)
title: this.$t('home')//home 自定义的
})
},
总结
提示:这里对文章进行总结:
例如:以上就是我写的多语言切换,希望可以帮到你们,注:有时候点击切换不生效可以用this.$router.go(0),location.reload()。