uniapp实现中英文切换功能
1.下载i18n包
npm install vue-i18n
2.创建目录,如:
lang.js
zh.js
export default {
hello: '登录',
// 其他中文文本...
}
eh.js
export default {
hello: 'Login',
// 其他英文文本...
}
3.mian.js引入
import VueI18n from 'vue-i18n'
import zh from './lang/zh'
import en from './lang/en'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh', // 默认语言为中文
messages: {
zh,
en
}
})
const app = new Vue({
...App,
i18n,
})
app.$mount()
4.页面
<template>
<view>
<text>{{ $t('login') }}</text> <!-- 使用 $t 方法获取对应语言的文本 -->
<!-- 其他组件内容... -->
</view>
</template>
5.切换
toggleLang() {
const currentLang = this.$i18n.locale;
if (currentLang === 'zh') {
this.$i18n.locale = 'en';
} else {
this.$i18n.locale = 'zh';
}
},
参考:参考链接