Vue3.0在组件外使用VueI18n的情况是什么

其他教程   发布日期:2025年03月19日   浏览次数:138

本篇内容主要讲解“Vue3.0在组件外使用VueI18n的情况是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue3.0在组件外使用VueI18n的情况是什么”吧!

    vue3.0在组件外使用VueI18n

    通常将写在setup里面的代码写在外面会报错

    Must be called at the top of a `setup`

    意思是必须写在setup里面

    要将 i18n 与 Vue 3 的组合 API 一起使用,但在组件的 setup() 之外,需要这么写

    1. // locales/setupI18n.ts
    2. import { App } from 'vue';
    3. import { createI18n } from 'vue-i18n'; // 引入vue-i18n组件
    4. import { messages } from './config';
    5. import globalConfig from '@/config/index';
    6. const {
    7. setting: { lang: defaultLang },
    8. } = globalConfig;
    9. // 注册i8n实例并引入语言文件
    10. const localeData = {
    11. legacy: false, // 使用CompotitionAPI必须添加这条.
    12. locale: defaultLang,
    13. messages,
    14. globalInjection: true,
    15. };
    16. export const i18n = createI18n(localeData);
    17. // setup i18n instance with glob
    18. export const setupI18n = {
    19. install(app: App) {
    20. app.use(i18n);
    21. },
    22. };

    这里是关键写法

    1. //某个组合式js文件
    2. //报错写法 Uncaught SyntaxError: Must be called at the top of a `setup`
    3. //import { useI18n } from 'vue-i18n'
    4. //const { t } = useI18n()
    5. //正确写法
    6. import { i18n } from '@/locales/setupI18n';
    7. const { t } = i18n.global;

    vue3使用vue-i18n国际化(多语言转换)

    提醒:vue3要使用vue-i18n必须要9以上的版本 npm install vue-i18n@9.2.2

    具体操作

    在src文件下新建一个lang文件夹,里面分别建好“cn.js”、“en.js”、 “index.js”三个文件

    cn.js和en.js中存放对应的翻译,例如:

    1. const messages = {
    2. home: {
    3. title: 'Book Store',
    4. hint: 'Computer Science And Software Engineering',
    5. guessYouLike: 'Guess You Like',
    6. }
    7. }
    8. export default messages
    9. const messages = {
    10. home: {
    11. title: '书城',
    12. hint: '计算机科学和软件工程',
    13. guessYouLike: '猜你喜欢'
    14. }
    15. }
    16. export default messages

    index.js中存放如下模板

    1. import { createI18n } from 'vue-i18n'
    2. import en from './en'
    3. import cn from './cn'
    4. const messages = {
    5. en, cn
    6. }
    7. const localeData = {
    8. legacy: false, // composition API
    9. globalInjection: true, //全局生效$t
    10. locale: cn, // 默认cn翻译
    11. messages
    12. }
    13. export function setupI18n (app) {
    14. const i18n = createI18n(localeData)
    15. app.use(i18n)
    16. }

    然后在main.js中使用setupI18n

    1. import { createApp } from 'vue'
    2. import App from './App.vue'
    3. import router from './router'
    4. import store from './store'
    5. import { setupI18n } from './lang/index'
    6. const app = createApp(App)
    7. app.use(store).use(router).mount('#app')
    8. setupI18n(app)

    使用的时候只需要在对应的地方写上 {{ $t("home.title") }} 就能使用了,需要特别注意的是必须使用$t开头,不能单独用t,如果需要单独用t的话需要其他的配置,直接用$t也比较方便,关于怎么单独使用t这里就不细说了

    1. <span class="ebook-popup-title-text">
    2. {{$t("home.title")}}
    3. </span>

    以上就是Vue3.0在组件外使用VueI18n的情况是什么的详细内容,更多关于Vue3.0在组件外使用VueI18n的情况是什么的资料请关注九品源码其它相关文章!