Home >Web Front-end >Vue.js >What is the situation when Vue3.0 uses VueI18n outside the component?
Usually if the code written in the setup is written outside, an error will be reported
Must be called at the top of a `setup`
It means it must be written in the setup
To use i18n with the Vue 3 combination API, but in the component In addition to setup(), you need to write like this
// locales/setupI18n.ts import { App } from 'vue'; import { createI18n } from 'vue-i18n'; // 引入vue-i18n组件 import { messages } from './config'; import globalConfig from '@/config/index'; const { setting: { lang: defaultLang }, } = globalConfig; // 注册i8n实例并引入语言文件 const localeData = { legacy: false, // 使用CompotitionAPI必须添加这条. locale: defaultLang, messages, globalInjection: true, }; export const i18n = createI18n(localeData); // setup i18n instance with glob export const setupI18n = { install(app: App) { app.use(i18n); }, };
Here is the key writing method
//某个组合式js文件 //报错写法 Uncaught SyntaxError: Must be called at the top of a `setup` //import { useI18n } from 'vue-i18n' //const { t } = useI18n() //正确写法 import { i18n } from '@/locales/setupI18n'; const { t } = i18n.global;
Reminder: vue3 must be used vue-i18n must be version 9 or above npm install vue-i18n@9.2.2
Create a new lang folder under the src file, and build "cn.js" in it. ", "en.js", and "index.js" three files
cn.js and en.js store the corresponding translations, for example:
const messages = { home: { title: 'Book Store', hint: 'Computer Science And Software Engineering', guessYouLike: 'Guess You Like', } } export default messages const messages = { home: { title: '书城', hint: '计算机科学和软件工程', guessYouLike: '猜你喜欢' } } export default messages
import { createI18n } from 'vue-i18n' import en from './en' import cn from './cn' const messages = { en, cn } const localeData = { legacy: false, // composition API globalInjection: true, //全局生效$t locale: cn, // 默认cn翻译 messages } export function setupI18n (app) { const i18n = createI18n(localeData) app.use(i18n) }
import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import { setupI18n } from './lang/index' const app = createApp(App) app.use(store).use(router).mount('#app') setupI18n(app)
in main.js. When using it, you only need to write {{ $t("home.title") }} in the corresponding place to use it. What needs special attention is that it must start with $t and cannot use t alone. If you need to use t alone, you need other configurations. It is more convenient to use $t directly. I won’t go into details here about how to use t alone.
<span class="ebook-popup-title-text"> {{$t("home.title")}} </span>
The above is the detailed content of What is the situation when Vue3.0 uses VueI18n outside the component?. For more information, please follow other related articles on the PHP Chinese website!