# i18n 国际化
(1)安装 i18n 插件
pnpm i install vue-i18n
(2)创建 i18n 目录
src/i18n
(3)编写文件
src/i18n/zh.ts
export default {
message: {
one: '一',
two: '二',
},
};
1
2
3
4
5
6
2
3
4
5
6
src/i18n/en.ts
export default {
message: {
one: 'one',
two: 'two',
},
};
1
2
3
4
5
6
2
3
4
5
6
src/i18n/index.ts
import { createI18n } from 'vue-i18n'
import zh from './zh'
import en from './en'
const language = (navigator.language || 'zh').toLowerCase()
const i18n = createI18n({
fallbackLocale: 'zh',
globalInjection: true,
legacy: false,
locale: language.split('-')[0] || 'zh',
messages: {
zh,
en,
},
})
export default i18n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(4)挂载 i18n
main.ts
import { createApp } from 'vue'
import './style.less'
import App from './App.vue'
import router from './router'
import i18n from "./i18n/index";
const app = createApp(App)
app.use(router)
app.use(i18n)
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
(5)组件内使用
<template>
<div class="home-page">
<button @click="change('zh')">中文</button>
<button @click="change('en')">english</button>
<p>{{ $t('message.one') }}</p>
<p>{{ $t('message.two') }}</p>
</div>
</template>
<script setup lang="ts">
import { onMounted, getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
onMounted(() => {
console.log('hello home page')
})
const change = (val: string) => {
proxy.$i18n.locale = val
}
</script>
<style lang="less" scoped>
.home-page {
font-size: 14px;
}
</style>
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
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
或者:
<template>
<div class="home-page">
<button @click="change('zh')">中文</button>
<button @click="change('en')">english</button>
<p>{{ $t('message.one') }}</p>
<p>{{ $t('message.two') }}</p>
</div>
</template>
<script setup lang="ts">
import { onMounted, getCurrentInstance } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { proxy } = getCurrentInstance()
onMounted(() => {
console.log('hello home page')
})
const change = (val: string) => {
proxy.$i18n.locale = val
}
</script>
<style lang="less" scoped>
.home-page {
font-size: 14px;
}
</style>
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
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
← 目录 keepAlive的使用 →