Vite vue-i18n TypeScript elementPlus 的坑

安裝版本的選擇

1
npm install vue-i18n@next --save

實踐上必須版本9以上

獨自拆成一個檔案 i18n.ts

引入要用的語系zh,en 為json的檔案
引入要用的語系zh,en 為json的檔案
*要把 legacy 設為 false,才可以使用 Composition API
在 src/ 目錄底下,新增 plugins/i18n.ts,設定語系並在main.ts引入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { createI18n } from 'vue-i18n'
import zh from '../lang/zh-TW.json'
import en from '../lang/en-US.json'

type MessageSchema = typeof zh

const i18n = createI18n<[MessageSchema], 'zh-TW' | 'en-US'>({
legacy: false, // 要把 legacy 設為 false,才可以使用 Composition API
locale: 'zh-TW', //
fallbackLocale: 'zh-TW',
globalInjection: true,//全域注入
messages: {
'zh-TW': zh,
'en-US': en
}
})
//輸出
export default i18n

新增zh-TW.json,en-US.json

在 src/ lang資料夾,新增 zh-TW.json 以及 en-US.json 兩個檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// zh-TW.json
{
"nav_menu":{
"home":"Home",
"login":"Login",
"register":"Register"
},
"form_validate":{
"PleaseConfirmPassword":"Please confirm password!",
"PleaseEnterPassword":"Please Enter Password!",
"PasswordCannotBeEmpty":"Password cannot be empty.!",
}
}

// zh-TW.json
{
"nav_menu":{
"home":"首頁",
"login":"登入",
"register":"註冊"
},
"form_validate":{
"PleaseConfirmPassword":"請再輸入一次密碼!",
"PleaseEnterPassword":"請輸入電子信箱!",
"PasswordCannotBeEmpty":"密碼不能為空!"
}
}