如何在vue3中使用后i18n

Vue3项目中插件不能全局引用了,要在页面内按需引入
因此在main.js/.ts中写的不生效

1)安装

npm install vue-i18n --save
  1. 在src文件夹下创建文件 src/i18nPlugin.js
import {
    
     ref, provide, inject } from "vue";
 
const createI18n = config => ({
    
    
  locale: ref(config.locale),
  messages: config.messages,
  $t(key) {
    
    
    return this.messages[this.locale.value][key];
  }
});
 
const i18nSymbol = Symbol();
 
export function provideI18n(i18nConfig) {
    
    
  const i18n = createI18n(i18nConfig);
  provide(i18nSymbol, i18n);
}
 
export function useI18n() {
    
    
  const i18n = inject(i18nSymbol);
  if (!i18n) throw new Error("No i18n provided!!!");
 
  return i18n;
}

3)准备翻译文件 cn.js en.js

const cn = {
    
    
    title: "标题",
}
export default cn;
const en = {
    
    
    title: "title",
}
export default en;

4)在App.vue中

<script>
  import {
    
     provideI18n } from "./i18nPlugin";
  import en from "./i18n/langs/en";
  import cn from "./i18n/langs/cn";

  export default {
    
    
    setup() {
    
    
      provideI18n({
    
    
        locale: "en",
        messages: {
    
    
          en: en,
          cn: cn
        }
      });
    }
  };
</script>

5)在组件中引入

<template>
  <div>
    <h2>{
    
    {
    
     i18n.$t('title') }}</h2>
    <button @click="switchLanguage">Switch language</button>
  </div>
</template>

<script>
  import {
    
     useI18n } from "./i18nPlugin";

  export default {
    
    
    setup() {
    
    
      const i18n = useI18n();

      const switchLanguage = () => {
    
    
        i18n.locale.value = i18n.locale.value === "en" ? "cn" : "en";
        //找地方保存一下修改的值
      };

      return {
    
    
        i18n,
        switchLanguage
      };
    }
  };
</script>

猜你喜欢

转载自blog.csdn.net/weixin_39423672/article/details/118327547