安装
npm i vue-i18n
创建目录
创建lang目录,目录下创建文件index.js
、en.js
、zhCn.js
// index.js
import {createI18n} from 'vue-i18n
import Cookies from'js-cookie
import zhCn from './zhCn
import en from'./en'
const messages ={
en,
zh CN': zhCn
}
const i18n = new createI18n({
locale: Cookies.get('language') || 'zh_CN',
messages
})
export default i18n
// en.js
export default {
login: 'login'
}
// zhCn.js
export default {
login: '登录'
}
main.ts配置
...
import i18n from '@/lang'
app.use(i18n)
...
template中使用
<template>
<button>{{ $t('login') }}</button>
</template>
封装
在js中使用跟vue2中的不一样,用起来有点麻烦,封装工具,创建i18n.js
import i18n from "@/lang
const { t } = i18n.global
export default t
在vue文件中的script里使用
<script setup>
...
import t from '@/utils/i18n' // 这里不能写作$t,即 import $t from '@/utils/i18n',会报错
t('login')
...
</script>
在单独script文件里使用
...
import $t from '@/utils/i18n' // 这里可以写作$t,也可以写作t
$t('login')
...