Nuxt Dynamic Routing on Firebase

扶醉桌前 提交于 2020-05-16 21:46:31

问题


My Nuxt.js App has this structure:

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

When user gets /{any_page}, it will use the path to build the page content:

/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.

When I try to run this using firebase functions:

$ 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?


回答1:


This answer only applies if using nuxt generate. If you're using nuxt build, this doesnt apply.

Generate says it skips over dynamic routes, unless you explicitly specify them, hence 404 errors. In your Nuxt config file, you want to specify those routes. 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.

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.



来源:https://stackoverflow.com/questions/57501556/nuxt-dynamic-routing-on-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!