nuxt.js安装国际化插件i18n
目录
nuxt.js安装国际化插件i18n
国际化i18n配置
- 安装依赖
npm install @nuxtjs/i18n
- 配置i18n
modules: [
'@nuxtjs/i18n'
],
i18n: {
langDir: '../locales/',
defaultLocale: 'zh',
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'i18n_redirected',
alwaysRedirect: true,
// redirectOn: 'root'
},
// strategy: 'prefix_except_default',
strategy: 'no_prefix',
locales: [
{
code: 'zh',
file: 'zh.ts',
name: '简体中文'
},
{
code: 'en',
file: 'en.ts',
name: 'English'
}
]
}
使用i18n
LanguageSwitcher.vue
<template>
<div class="language-switcher">
<select v-model="locale" @change="switchLanguage">
<option
v-for="lang in availableLocales"
:key="lang.code"
:value="lang.code"
>
{{ lang.name }}
</option>
</select>
</div>
</template>
<script setup lang="ts">
const { locale, locales } = useI18n()
const switchLocalePath = useSwitchLocalePath()
const router = useRouter()
const availableLocales = computed(() => {
return (locales.value).map(l => {
return {
code: l.code,
name: l.name
}
})
})
const switchLanguage = () => {
const path = switchLocalePath(locale.value)
if (path) {
router.push(path).then(() => {
window.location.reload() // 强制刷新页面
})
}
}
</script>
<style scoped lang="less">
.language-switcher {
select {
padding: @spacing-sm @spacing-md;
border: 1px solid @border-color;
border-radius: @border-radius-md;
background-color: transparent;
color: @light-text-color;
cursor: pointer;
&:hover {
border-color: @secondary-color;
}
option {
padding: 10px;
background-color: @primary-color;
color: @light-text-color;
}
}
}
</style>
创建语言文件
/locales/en.ts
export default {
welcome: 'Welcome',
nav: {
home: 'Home',
about: 'About'
},
content: {
title: 'My Project',
body: 'This is a project built with Nuxt3',
footer: '© 2024 All rights reserved'
},
sidebar: {
left: 'Left Sidebar',
right: 'Right Sidebar'
}
}
/locales/zh.ts
export default {
welcome: '欢迎',
nav: {
home: '首页',
about: '关于'
},
content: {
title: '我的项目',
body: '这是一个使用 Nuxt3 构建的项目',
footer: '© 2024 版权所有'
},
sidebar: {
left: '左侧栏目',
right: '右侧栏目'
}
}
在需要国际化的地方通过{ { $t(‘sidebar.right’) }}的形式来使用
运行项目后,可以引入切换按钮进行语言切换
ps:切换语言后需要刷新页面才会正确显示