使用
- 第一步:
npm install vue-i18n@next
或yarn add vue-i18n@next
- 第二步:在
src
目录下新建lang
并新建index.js
文件
下面是 src/lang/index.js
代码
import {
createI18n } from 'vue-i18n'
export default createI18n({
legacy: false, // 让 setup 函数可以通过 t 访问
globalInjection: true, // 让 template 可以像 vue2 那样使用 $t 来访问
locale: 'zh-cn',
fallbackLocale: 'zh-cn',
messages: {
'zh-cn': {
index: {
title: '你好,vue-i18n'
}
},
'en-us': {
index: {
title: 'Hello, Vue-i18n'
}
}
}
})
- 第三步:在入口文件
main.js
里引入进来
import {
createApp } from 'vue'
import App from '@/App.vue'
import i18n from '@/lang/'
const app = createApp(App)
app
// ...
.use(i18n)
.mount('#app')
export default app
至此就完成啦
使用
下面是 setup()
和 template
如何进行访问多语言
- setup
setup
可通过导入t()
来访问 - template
template
可通过旧版本写法即$t()
来访问
代码如下
<template>
<h2>访问方式1:{
{
title }}</h2>
<h2>访问方式2:{
{
$t('index.title') }}</h2>
</template>
<script>
import {
useI18n } from 'vue-i18n'
export default {
setup() {
const {
t } = useI18n()
const title = t('index.title')
return {
title
}
}
}
</script>
效果图
好了,内容就这里,关于如何切换多语言就按照平时那样去写就行了都一样的,这里不再啰嗦啦。
另外笔者还整理了 Vue3 学习指南总结,有兴趣的话可以去瞧一瞧。