nuxt-i18n中持久化语言变更方法的执行位置咨询
Hey there! Let's break down why you're running into this error and get your language cookie persistence working correctly.
The Root of the Error
First off, the issue with your current code is twofold:
- You're using
:click(which is for binding a property) instead of@click(which is for listening to the click event) on your<nuxt-link>. - Trying to call
this.$i18ndirectly in the template's event binding can lead to context issues, especially since<nuxt-link>is a component with its own scope.
The Correct Approach
Instead of shoving the cookie logic directly into the template, let's move it to a reusable method in your component. Here's how to fix it step by step:
1. Update the Template
Replace the :click binding with @click, and call a dedicated method to handle setting the cookie:
<nuxt-link class="px-6 py-2 block" v-for="locale in availableLocales" :key="locale.code" :to="switchLocalePath(locale.code)" @click="persistLocale(locale.code)" > {{ locale.code.toUpperCase() }} </nuxt-link>
2. Add the Method to Your Component
Create a persistLocale method in the methods section where you'll safely call $i18n.setLocaleCookie:
export default { computed: { availableLocales () { return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale) } }, methods: { persistLocale(locale) { this.$i18n.setLocaleCookie(locale) } } }
Alternative: Full Control Over Navigation
If you want to ensure the cookie is set before navigation happens, you can ditch <nuxt-link> and handle the route push yourself. This avoids any potential race conditions:
<a class="px-6 py-2 block" v-for="locale in availableLocales" :key="locale.code" @click="switchAndPersistLocale(locale.code)" > {{ locale.code.toUpperCase() }} </a>
Then update your methods:
methods: { switchAndPersistLocale(locale) { // Set the cookie first this.$i18n.setLocaleCookie(locale) // Then navigate to the localized route this.$router.push(this.switchLocalePath(locale)) } }
Why This Works
By moving the cookie logic into a component method, you ensure you're accessing this.$i18n in the correct component context, eliminating the "undefined" error. Plus, using @click properly listens for the user's click event instead of trying to bind a property.
内容的提问来源于stack exchange,提问作者royketelaar

