Loading...

文章背景图

[学习,记录,整理] Nuxt处理i18n及路由

2022-10-24
2332
-
- 分钟

创建Nuxt项目

npm init nuxt-app <project-name>

i18n

引入i18n库

npm install @nuxtjs/i18n

添加i18n配置

nuxt.config.js

export default {
    ...
    modules: [
        ...
        '@nuxtjs/i18n'
    ],
    i18n: {
        // 提供支持的语言
        locales: ['en', 'zh', 'tw'],
        // 直接从 / 访问时使用的默认语言
        defaultLocale: 'en',
        vueI18n: {
            // 当访问某个语言时找不到对应的配置,使用一个指定的语言进行替代
            fallbackLocale: 'en',
            messages: {
                en: {
                    welcome: 'Welcome to your Nuxt Application',
                    fb: 'fallback'
                },
                zh: {
                    welcome: '欢迎来到你的Nuxt应用程序',
                    fb: '回落'
                },
                tw: {
                    welcome: '歡迎來到你的Nuxt應用程式'
                }
            }
        },
        // 使用cookie缓存切换的语言
        detectBrowserLanguage: {
            useCookie: true,
            cookieKey: 'custom_cookie'
        }
    }
}

在页面中使用

components/Tutorial.vue

<template>
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 sm:items-center sm:pt-0">
        <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.1.2/dist/tailwind.min.css" rel="stylesheet">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            ...
            <div class="mt-8 bg-white overflow-hidden shadow sm:rounded-lg p-6">
                <h2 class="text-2xl leading-7 font-semibold">
                    {{ $t("welcome") }}
                </h2>
                ...
                <div class="text-center mt-4">
                    <nuxt-link :to="localePath('index', 'en')">English</nuxt-link>
                    <nuxt-link :to="localePath('index', 'zh')">简体中文</nuxt-link>
                    <nuxt-link :to="localePath('index', 'tw')">繁體中文</nuxt-link>
                    <p>{{ $t("fb") }}</p>
                </div>
            </div>
            ...
        </div>
    </div>
</template>

$tlocalePathswitchLocalePath等方法由@nuxtjs/i18n挂在到Vue对象/原型上,可以直接使用。


参考

nuxt-i18n-module

评论交流

文章目录