如何在nuxt-i18n中同时使用指定nuxt-link,实现切换语言时自动跳转至对应语言的About页面?
Got it, let's tackle this problem. You want clicking the language switch link to take you directly to the corresponding language version of the About page instead of the homepage, right? Here's how to make that work with nuxt-i18n:
Core Concept
The switchLocalePath and localePath methods from nuxt-i18n support additional parameters to specify the target page you want to navigate to after switching languages. Instead of just passing the language code, you can pair it with the About page's path or route name.
Method 1: Directly Navigate to About Page (Any Current Page)
If you want to jump to the About page's localized version no matter which page you're on now, use this syntax:
<!-- Switch to English About page --> <nuxt-link :to="switchLocalePath('en', '/about')">EN</nuxt-link> <!-- Switch to your other language's About page (adjust code to match your config) --> <nuxt-link :to="switchLocalePath('zh', '/about')">中文</nuxt-link>
The second argument in switchLocalePath is the target page path. nuxt-i18n will automatically convert this to the localized route (e.g., /en/about for English, /zh/about for Chinese based on your setup).
Method 2: Stay on Localized About Page (When Already on About)
If you're already on the About page and want switching languages to keep you on the localized About page (instead of jumping to homepage), pass the current route object as the second argument:
<nuxt-link :to="switchLocalePath('en', $route)">EN</nuxt-link>
This works for any page—if you're on the homepage, it'll switch to the localized homepage; if you're on About, it stays on the localized About.
Alternative: Use localePath with Target Language
You can also achieve the same result using localePath by explicitly specifying the target language as the second parameter:
<nuxt-link :to="localePath('/about', 'en')">EN</nuxt-link>
Bonus: Use Localized Route Names (More Flexible)
If you've set up named routes in your nuxt-i18n config (recommended for scalability), you can use the route name instead of the path:
<nuxt-link :to="switchLocalePath('en', { name: 'about' })">EN</nuxt-link>
This way, if you ever change the About page's URL structure, you won't need to update every language switch link in your templates.
Quick Check for Your Config
Make sure your nuxt-i18n setup includes the necessary locales and routing config (example snippet from nuxt.config.js):
export default { modules: ['nuxt-i18n'], i18n: { locales: [ { code: 'en', name: 'English', file: 'en.js' }, { code: 'zh', name: '中文', file: 'zh.js' } ], defaultLocale: 'en', vueI18n: { fallbackLocale: 'en' } } }
That's all! Pick the method that fits your use case, and you'll have language switching that lands directly on the localized About page.
内容的提问来源于stack exchange,提问作者karzol73

