前言
由于Nuxt3不支持直接使用vue-i18n,后面在Nuxt官网发现Nuxt官方出了一个基于vue-i18n做的一个支持Nuxt3的库 Nuxt I18n。
一、安装和引入
首先我们通过 npx nuxi@latest module add i18n安装该模块。
然后在nuxt.config.ts文件中的modules引入并可以在i18n这个对象里对语言包进行自定义配置。
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n'],
i18n: {
// Module Options
}
})
二、在项目中使用
在根目录下新建一个文件夹locales用于存放各国的语言包。
// en.json
{
"welcome": "welcome",
"home": "home"
}
// zh.json
{
"welcome": "欢迎",
"home": "首页"
}
在根目录新建i18n.config.ts文件,导入存放在locales下的语言包对i18n进行配置。
// i18n.config.ts
import zh from './locales/zh.json'
import en from './locales/en.json'
export default defineI18nConfig(() => ({
locale: 'zh', //默认语言
messages: { //将本地语言包与该模块绑定
en,
zh
}
}))
初始化语言,我们可以通过浏览器apinavigator.language获取用户的首选语言,然后对项目使用语言进行初始化,其中import.meta.client是Nuxt中用于判断当前随处环境是否为客户端的一个api。
<script setup lang="ts">
import { LANG_LIST } from '../locales/list';
const { setLocale } = useI18n()
function setLang(): void {
if (import.meta.client) {
let navLang = navigator.language
for (let i = 0; i < LANG_LIST.length; i++) {
if (navLang.includes(LANG_LIST[i])) {
setLocale(LANG_LIST[i])
}
}
}
}
setLang()
</script>
在项目里通过$t('')的方式使用该模块。
<template>
<div class="index">
<h1>{{ $t('home') }}</h1>
</div>
</template>