vue3+vite---vueI18n使用
下载yarn add vue-i18n@9
配置文件
js
//zh.js
export default {
login: {
username: '用户名',
password: '密码',
SignIn: '登录',
NoAccount: '没有账号? 去注册!',
},
};
//en.js
export default {
login: {
username: 'username',
password: 'password',
SignIn: 'sign in',
NoAccount: 'No account? To register',
},
};
js
import { createI18n } from 'vue-i18n';
import zh from './zh';
import en from './en';
const messages = {
zh: { ...zh },
en: { ...en },
};
const i18n = createI18n({
locale: 'en',
messages,
});
export default i18n;
//main.js
import i18n from '@/plugins/vue-i18n';
import { createApp } from 'vue';
const app = createApp(App);
app.use(i18n).mount('#app');
使用
../.jsx
js
import { defineComponent } from 'vue';
import { useI18n } from 'vue-i18n';
export default defineComponent({
setup(){
const { t } = useI18n();
return ()=>(<div>{t('login.username')}</div>)
}
})
语言切换
js
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
// 切换语言的方法
const {locale} = useI18n()
// 绑定单机事件,lang代表语言简写,传递zh或en
const handleSetLanguage = lang => {
locale.value = lang
ElMessage.success('更新成功')
}
报错解决
打开浏览器控制台会出现如下错误:You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
安装intlify/vite-plugin-vue-i18n
yarn add intlify/vite-plugin-vue-i18n
在vite.confing.js
中设置
js
import path from "path"
import vueI18n from '@intlify/vite-plugin-vue-i18n'
export default defineConfig({
plugins: [
vue(),
vueI18n({
include: path.resolve(__dirname,'./path/to/src/locales/**')
})
]
})
WARNING
关于vuei18n
中在组合式api中使用tc
函数复数功能, 官方文档给出的例子: 导出t
自useI18n
(对于 Composition API 模式)
同 vue-i18n, useI18n 返回一个 i18n 实例,该实例提供文案翻译 API 例如 t 方法,相较于选项式 API 中的翻译方法,在组合式 API 中有部分变化。
- 翻译方法 $t/t 和 $tc/tc,在组合式 API 中统一使用翻译方法 t
- 翻译方法 $te/te,在组合式 API 中统一使用 te
- 翻译方法 $tm/tm,在组合式 API 中统一使用 tm
useI18n
方法的执行必须在 setup
中的顶层。
但是目前在测试中发现,在本地开发时t()函数使用复数功能时没有问题,但是打包完成后部署却发现翻译失效(暂未找到解决办法)