1.安装vue-i18n依赖
yarn add vue-i18n 或者 npm install vue-i18n --save-dev
2.创建文件夹locales,创建3个文件分别为index.ts;en.ts;zh.ts
如图:
代码如下
index.ts
import { createI18n } from 'vue-i18n'
// 引入各个语言配置文件
import zh from './zh-cn'
import en from './en'
const i18n = createI18n({
legacy: false, // Composition API 模式
globalInjection:true, // 全局注册 $t方法
locale: 'zh', //默认显示的语言
messages:{
zh,
en
}
})
export default i18n;
en.ts
export default {
routes: {
home: 'Home',
register: 'Register',
logout: 'Log out',
},
page: {
I: 'I'
}
}
zh-cn.ts
export default {
routes: {
home:'首页',
register:'注册',
logout:'退出登录',
},
page:{
I: '我'
}
}
3.在main.ts中引入及注册vue-i18n
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './style/index.scss'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import i18n from "./locales/index"; //引入i18n组件
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(router).use(ElementPlus).use(i18n).mount('#app')
4.页面中使用
<template>
<div>
这个页面是要做统计图的 {{$t("page.I")}
</div>
</template>
<script>
export default {
name: "Home",
components: { },
}
</script>
<style scoped>
</style>