A, install,

 npm install vue-i18n@next
Copy the code

OR

yarn add vue-i18n@next
Copy the code

PS: My version is 9.1.6

Second, the use of

1. InsrcNew directorylanguageFolder (as shown below)

PS: if you don't have TS installed, you can use JS

In 2.languageNew folderindex.ts en-US.ts zh-CN.tsThree files

//en-US.ts
export default  {
  / / name
  'name': 'peng-xiao-hei' 
}
Copy the code
//zh-CN.ts
export default  {
  / / name
  'name': 'Peng Xiaohei' 
}
Copy the code

PS: VITE import.meta.globEager is used here. Non-vite can use require.context

//index.ts
import { createI18n } from 'vue-i18n'		// Introduce vuE-i18n
// Import files in the same directory
const modules = import.meta.globEager('./*')

/ / if you have other language files in the directory Its path is the SRC/views/home/locales/en - US ts
// Then you can use :lower: (lowercase) :upper: (uppercase) to import files
const viewModules = import.meta.globEager('.. /views/**/locales/[[:lower:]][[:lower:]]-[[:upper:]][[:upper:]].ts')

function getLangAll() :any{
  let message:any = {}
  getLangFiles(modules,message)
  getLangFiles(viewModules,message)
  return message
}
/** * get all language files *@param {Object} mList* /
function getLangFiles(mList:any,msg:any){
  for(let path in{mList),if(mList[path].default){
      // Get the file name
      let pathName = let pathName = path.substr(path.lastIndexOf('/') + 1.5)
      
      if(msg[pathName]){ msg[pathName] = { ... mList[pathName], ... mList[path].default } }else{
        msg[pathName] = mList[path].default
      }
      
    }
  }
}

  // Register the i8n instance and import the language file
 const i18n = createI18n({
    legacy: false.locale: 'zh-CN'.messages: getLangAll()
  })
  
  export default i18n; // Expose i18n and introduce mount in main.js
Copy the code

3. The main registration

//main.ts
import VueI18n from './language'

let app = createApp(App);
app.use(VueI18n)
Copy the code

4. Page usage

//home.vue
<template>
    <div>{{t('name')}}</div>
</template>

<script>
import { useI18n } from "vue-i18n";

export default defineComponent({
    setup() {
        const { t } = useI18n();
        return{
            t
        }
   }
})
</script>
Copy the code

Source code address: github.com/Peng-Xiao-S…

IO/vite-vuE-ad…