i18n+vue3+uniapp国际化(语言切换)
1. 安装vue-i18n
. npm install vue-i18n --save
2. 创建locales文件
- 在目录下创建locales文件夹(与pages同级)放入应该index.ts文件 代码如下
import { createI18n } from "vue-i18n"
import zh from "./lang/zh"
import en from "./lang/en"
// console.log("当前系统语言", uni.getLocale())
const defaultLang = uni.getStorageSync("lang") || "zh"
// console.log("当前系统语言", defaultLang, typeof defaultLang)
const i18n = createI18n({
locale: defaultLang || "zh",
messages: {
en,
zh
},
fallbackLocale: "zh", // 回退语言
legacy: false
})
export default i18n
- 在locales创建文件夹lang,创建两个文件en和zh对应中英文配置文件结构如下
英文文件
// en.ts
const locale = {
index: {
title: "hello"
}
}
export default locale
中文文件
// zh.ts
const locale = {
index: {
title: "欢迎"
}
}
export default locale
3.在main文件中引入
import { createSSRApp } from 'vue'
import VueI18n from "@/locales" // 引入i18n
export function createApp() {
const app = createSSRApp(App)
app.use(VueI18n)
return {
app
}
}
4.在页面中使用
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{t("index.title") }}</text>
//切换语言
<button @click="switchLang('zh')">中文</button>
<button @click="switchLang('en')">英文</button>
</view>
</view>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n" // 使用vue-i18n的useI18n方法
import { onMounted, ref } from 'vue';
onMounted(()=>{
uni.setNavigationBarTitle({ title: t("index.title") }) //修改当前页面的标题(中英文)
uni.setTabBarItem({//修改tabbar的名称(中英文)
index: 0,//tabbar的坐标(第几个)
text: t("index.title"),//需要修改的文字
})
})
const { locale, t } = useI18n()
//切换语言
const switchLang=(lang:any)=>{
locale.value = lang;
//以上只需要页面上的中英文
//以下是需要切换页面标题和tabbar时候刷新的操作
uni.setStorageSync("lang",lang)
uni.redirectTo({
url: '/pages/index/index'
})
}
</script>