简体   繁体   English

Firebase 上的 Nuxt 动态路由

[英]Nuxt Dynamic Routing on Firebase

My Nuxt.js App has this structure:我的 Nuxt.js 应用程序具有以下结构:

/pages/index.vue
/pages/_slug/index.vue

When user gets /{any_page} , it will use the path to build the page content:当用户获取/{any_page} ,它将使用路径来构建页面内容:

/pages/_slug/index.vue /pages/_slug/index.vue

<template>
  <div>
    {{slug}}
  </div>
</template>

<script>
import fetch from 'isomorphic-fetch';
export default {
  async asyncData({ params }) {
    return { slug: params.slug } 
  }
}
</script>

This works perfectly when running the Nuxt App directly via yarn dev .这在通过yarn dev直接运行 Nuxt App 时非常有效。

When I try to run this using firebase functions:当我尝试使用 firebase 函数运行它时:

$ firebase serve --only functions,hosting

The static routes work perfectly, but the dynamic routes always render the default / page, instead of executing the dynamic one.静态路由完美运行,但动态路由总是呈现默认/页面,而不是执行动态路由。 How do I fix this?我该如何解决?

If using nuxt generate , then the explanation below should work.如果使用nuxt generate ,那么下面的解释应该有效。 If using nuxt build , look at this repo, it is a template i wrote for nuxt + firebase as ssr.如果使用nuxt build ,请查看repo,它是我为 nuxt + firebase 作为 ssr 编写的模板。

Generate says it skips over dynamic routes, unless you explicitly specify them, hence 404 errors. Generate表示它会跳过动态路由,除非您明确指定它们,因此会出现 404 错误。 In your Nuxt config file, you want to specify those routes.在您的 Nuxt 配置文件中,您希望指定这些路由。 Here is an example of fetching from the database during generation.这是在生成期间从数据库中获取的示例。 Note that in my example below, the doc id is the slug for the page.请注意,在我下面的示例中,文档 ID 是页面的 slug。

nuxt.config.js nuxt.config.js

generate: {
    async routes() {
      const { db } = require('./services/fireInit');
      const qs = await db.collection('recipes').get();
      return qs.docs.map(x => `/recipes/${x.id}`);
    }
  },

The downside to this approach is as you add new items via a CMS, you will need to rebuild/deploy your site each time if you want to be able to use these new links without a 404. CMS without redeploy does work if you navigate to new content 'organically'...404 only occurs on a page refresh or on jumping directly to the page from a hyperlink.这种方法的缺点是,当您通过 CMS 添加新项目时,如果您希望能够在没有 404 的情况下使用这些新链接,则每次都需要重建/部署您的站点。如果您导航到新内容“有机”...404 仅在页面刷新或从超链接直接跳转到页面时发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM