我正在使用asyncData
slug 来获取页面的当前数据,以在我的 API (Strapi) 中查找数据。这适用于新页面加载,但在导航到另一种语言 (nuxt-i18n) 时会失败。当导航到另一种语言时,调用了 asyncData 但由于某种原因尚未更新路由,因此 slug 匹配失败。手动刷新页面会更新路由,然后 slug 匹配。
// pages/_slug/index.vue
<script>
export default {
async asyncData({ params, route, $strapi, error, app, store, i18n }) {
const path = route.params.slug // <- This is not updated on page navigation using language switcher
const page = await $strapi.$pages.find({ slug: path, _locale: i18n.locale })
if (page.length === 0) {
error({ statusCode: 404, message: 'Page not found' })
return {}
}
// Get the slug for this page in every locale.
const localizedSlugs = {}
for (const code of i18n.localeCodes) {
localizedSlugs[code] = {
slug: route.params.slug,
}
}
for (const lang of page[0].localizations) {
const pageLocalized = await $strapi.$pages.find({ id: lang.id, _locale: lang.locale })
if (pageLocalized.length > 0) {
localizedSlugs[lang.locale].slug = pageLocalized[0].slug
}
}
await store.dispatch('i18n/setRouteParams', localizedSlugs)
return { page: page[0] }
}
}
</script>
我正在使用的语言切换器如下所示:
<template>
<div class="language-switcher">
<nuxt-link
v-for="locale in availableLocales"
:key="locale.code"
:to="switchLocalePath(locale.code)">
{{ locale.code }}
</nuxt-link>
</div>
</template>
<script>
export default {
computed: {
availableLocales() {
return this.$i18n.locales
},
},
}
</script>
知道为什么route.params.slug
(或通常的路线)在客户端导航到不同语言后没有更新吗?
编辑:我目前的解决方法是不使用NuxtLink
组件,而是使用普通的锚标签,如下所示:
<a
v-for="locale in availableLocales"
:key="locale.code"
:href="switchLocalePath(locale.code)">
{{ locale.code }}
</a>
这会重新加载页面并正确加载asyncData
依赖于将页面与 API 匹配的路由参数。