【问题标题】:Nuxt context.route not updated in asyncData()Nuxt context.route 未在 asyncData() 中更新
【发布时间】:2021-07-18 06:26:51
【问题描述】:

我正在使用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 匹配。

【问题讨论】:

标签: nuxt.js nuxt-i18n


【解决方案1】:

更新:问题已在vue-i18n@8.24.5修复


原答案

你用的是什么版本的 nuxt-i18n 和 vue-i18n?

我在使用 nuxt validate() 时遇到了同样的问题:从 nuxt 上下文获取路由并将其与 vuex 存储中的 API 数据匹配失败,因为路由未更新。

对我来说,它可以降级到vue-i18n@8.24.2 或更低。看起来这是从 8.24.3 开始的问题。

我在这里https://github.com/kazupon/vue-i18n/issues/1230 提出了一个问题,但我不确定它是由 vue-i18n 还是 nuxt-i18n 解决的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2021-07-26
    • 2019-05-03
    • 2021-02-15
    • 2021-06-21
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多