首頁  >  文章  >  web前端  >  Vue3.0在元件外使用VueI18n的情況是什麼

Vue3.0在元件外使用VueI18n的情況是什麼

PHPz
PHPz轉載
2023-05-17 17:01:061824瀏覽

    vue3.0在元件外使用VueI18n

    通常將setup裡面寫的程式碼寫在外面會報錯

    #Must be called at the top of a `setup`

    意思是必須寫在setup裡面

    要將i18n 與Vue 3 的組合API 一起使用,但在組件的setup() 之外,需要這麼寫

    // 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);
      },
    };

    這裡是關鍵寫法

    //某个组合式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;

    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中存放對應的翻譯,例如:

    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

    index.js中存放如下模板

    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)
    }

    然後在main.js中使用setupI18n

    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)

    使用的時候只需要在對應的地方寫上{{ $t("home.title") }} 就能使用了,需要特別注意的是必須使用$t開頭,不能單獨用t,如果需要單獨用t的話需要其他的配置,直接用$t也比較方便,關於怎麼單獨使用t這裡就不細說了

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

    以上是Vue3.0在元件外使用VueI18n的情況是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除