美文网首页
Vue3.x 相关知识点

Vue3.x 相关知识点

作者: Viewwei | 来源:发表于2021-03-12 20:15 被阅读0次
    • 删除的api
      Vue3对于attrs还是可以用的,listeners已经移除,不能使用
    • Vue中使用Vue-i18的使用
      在创建好Vue+typescript项目之后执行以下指令
    vue add vue-i18n
    

    系统会创建一个i18n文件,代码如下

    import { createI18n, LocaleMessages, VueMessageType } from 'vue-i18n'
    function loadLocaleMessages(): LocaleMessages<VueMessageType> {
      const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
      const messages: LocaleMessages<VueMessageType> = {}
      locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
          const locale = matched[1]
          messages[locale] = locales(key).default
        }
      })
      return messages
    }
    const i18n= createI18n({
      globalInjection: true ,
      locale: 'zh',
      fallbackLocale: 'zh',
      messages: loadLocaleMessages()
    })
    export default i18n
    
    

    locale:表示当前支持的语言
    fallbackLocale:没有设置该语言时候,使用什么语言
    messages:国际化的配置信息

    • 注意
      messages的信息并不需要像系统那么配置,自己也可以手动配置。只要保证messages的结构类似如下结构
    {
      "zh":{
    //中文
        },
    "ch":{
    //繁体
    }
    }
    

    如果没有配置 locale messages 它会已vue.config,.js中的为主

        pluginOptions: {
          i18n: {
            locale: 'en',
            fallbackLocale: 'en',
            localeDir: 'locales',
            enableLegacy: true,
            runtimeOnly: false,
            compositionOnly: true,
            fullInstall: true
          }
        },
    
    
    • 特别注意
      globalInjection需要设置,不然在界面引用的时候会报错

    装饰器中使用国际化

    在装饰器中如果想使用i18n,那么需要取打开$t方法,如下所示

    t: (t: string) => string = getCurrentInstance()?.appContext.config
        .globalProperties!.$t;
    

    让调用t方法就可以了

    普通ts文件使用

    实现导入创建i18n的文件,然后调用global.t方法

    import i18n from "@/i18n"
    //调用
    i18n.global.t("message")
    

    相关文章

      网友评论

          本文标题:Vue3.x 相关知识点

          本文链接:https://www.haomeiwen.com/subject/crazqltx.html