nuxt.config.js
// https://nuxt.com/docs/api/configuration/nuxt-config
import path from 'path'
export default defineNuxtConfig({
modules:[
'@nuxtjs/i18n',
],
i18n: {
// 必需配置
locales: [
{ code: 'en', iso: 'en-US', file: 'en.json', name: 'English' },
{ code: 'zh', iso: 'zh-CN', file: 'zh.json', name: '中文' }
],
defaultLocale: 'en', // 默认语言
lazy: true, // 懒加载翻译文件
langDir: path.resolve(__dirname, 'i18n'), // 绝对路径 // 翻译文件目录(根目录下)
},
tailwindcss: {
viewer: false
}
})
i18n文件夹下创建 en.json
{
"welcome": "Hello, World!",
"button": {
"submit": "Submit"
}
}
zh.json
{
"welcome": "你好,世界!",
"button": {
"submit": "提交"
}
}
app.vue
<template>
<div class="flex justify-between items-center">
<div>
<button @click="setLocale('en')">English</button>
<button @click="setLocale('zh')">中文</button>
<h1>{{ $t('welcome') }}</h1>
<button>{{ $t('button.submit') }}</button>
</div>
</div>
</template>
<script setup>
const { t,setLocale } = useI18n()
</script>