你已经实例化了i18n
在您的应用程序上,在main.js
。这是重要的一点。
文档中提供的示例不一定必须在内部定义的实例上完成createApp
。它可以在任何组件中工作,只要你已经实例化了 i18nmain.(js|ts)
这将适用于任何组件(无论您需要什么地方t
):
import { useI18n } from "vue-i18n";
export default defineComponent({
setup() {
const { t } = useI18n();
// you can now use t('some.text.to.be.translated')
// t('some.text.to.be.pluralized', { n: 1 }, 1);
return {
// expose `t` to <template>:
t,
}
},
// if you want it inside any method, computed or hook
// in case you still use Options API
computed() {
someTranslatedText() {
return useI18n().t('translate.me');
}
},
methods: {
methodNeedingTranslation() {
const { t } = useI18n();
// do stuff with `t`
}
}
})
旁注:全部$tc
(多元化) 功能已移至t
.
如果您要升级现有应用程序并且不想遍历模板并替换所有实例$t
and $tc
with t
:
setup: () => ({
$t: useI18n().t
$tc: useI18n().t
})
To make $t
and $tc
可在任何组件中使用<template>
,无需导入+暴露它们<script>
(or <script setup>
):
import App from './App.vue'
import { useI18n } from 'vue-i18n'
const app = createApp(App);
app.config.globalProperties.$t = useI18n().t
- 如果您仍然需要它们
<script>
, 进口于'vue-i18n'
,如上图所示。
-
$tc
Vue3 中不再使用。如果你的模板来自Vue2,最好替换所有$tc
's with $t
。或者你可以分配useI18n().t
对于两者,如果您不想触摸模板:
Object.assign(app.config.globalProperties, {
$t: useI18n().t,
$tc: useI18n().t
})