我的项目中的全局语言切换是基于Vue I18n和vuex实现的。
首先说明怎么进行语言切换
1.下载Vue I18n插件
npm install vue-i18n
2.配置main.js
import App from './App'
import Vue from 'vue'
import store from './store'; // 引入 Vuex 存储
import VueI18n from 'vue-i18n';
// 导入语言文件
import en from './static/lang/en.json';
import zh from './static/lang/zh.json';
Vue.use(VueI18n);
//配置 Vue I18n
const messages = {
en,
zh
};
const i18n = new VueI18n({
locale: store.state.app.locale, // 设置默认语言
messages
});
// 监听 Vuex 中的语言变化
store.watch(
(state) => state.app.locale,
(newLocale) => {
i18n.locale = newLocale; // 更新 Vue I18n 的语言
}
);
const app = new Vue({
...App,
store, // 将 Vuex 存储挂载到 Vue 实例上
i18n // 将i18n挂载到Vue实例上
});
app.$mount();
其中en,zh用于定义两种语言的翻译内容
en.json
{
"home_cell_list": {
"all_orders": "All Orders",
"my_reports": "My Reports",
"identity_verification": "Identity Verification",
"user_settings": "User Settings",
"settings": "Settings",
"my_collections": "My Collections",
"frequently_asked_questions": "Frequently Asked Questions",
"english": "English",
"chinese": "Chinese",
"logout": "Logout"
},
"tabbar": {
"index": "Home",
"class": "Class",
"home": "My"
}
}
zh.json
{
"home_cell_list": {
"all_orders": "全部订单",
"my_reports": "我的报告",
"identity_verification": "身份认证",
"user_settings": "用户设置",
"settings": "设置",
"my_collections": "我的收藏",
"frequently_asked_questions": "常见问题",
"english": "English",
"chinese": "中文",
"logout": "退出登录"
},
"tabbar": {
"index": "首页",
"class": "分类",
"home": "我的"
}
}
其中locale用于设置语言种类,为了全局切换语言种类,将数据存储到vuex中
locale
const state = {
locale: 'zh',
};
const mutations = {
setlocale_m(state, locale) {
state.locale = locale
}
};
const actions = {
setlocale_a({
commit
}, locale) {
commit('setlocale_m', locale)
}
};
export default {
state,
mutations,
actions
};
3.使用Vue I18n插件
<template>
<view>
<view>{{ $t('home_cell_list.all_orders') }}</view>
<view class="list">
<u-cell-group>
<u-cell v-for="(item,index) in list" :title="$t(item.text)" :border="false"
:isLink="true" :key="index" @click="to(item)">
</u-cell>
</u-cell-group>
</view>
<button @click="handleselect('en')">English</button>
<button @click="handleselect('zh')">中文</button>
</view>
</template>
<script>
import store from '@/store';
import {
mapActions
} from 'vuex';
export default {
data() {
return {
loginlist: [{
text: 'home_cell_list.all_orders'
},
{
text: 'home_cell_list.my_reports'
},
{
text: 'home_cell_list.user_settings'
},
{
text: 'home_cell_list.my_collections'
},
{
text: 'home_cell_list.frequently_asked_questions'
},
{
text: 'home_cell_list.settings'
},
{
text: 'home_cell_list.logout'
}
]
}
},
methods: {
...mapActions(['setlocale_a'),
//切换语言
handleselect(x) {
//通过this.setlocale_a修改vuex中的local,结合main.js中的
//const i18n = new VueI18n({
//locale: store.state.app.locale,
//messages
//});
//来改变全局的语言种类
if (x== 'en') {
this.setlocale_a('en')
} else {
this.setlocale_a('zh')
}
}
}
}
</script>
注 vuex请自己写,我的vuex进行了模块化,直接复制代码可能会报错,当然也可以参考我的‘vuex的模块化’这篇文章
603

被折叠的 条评论
为什么被折叠?



