2

I use gridsome-source-mysql plugin to get data from MySQL.

The articles has more than 50 categories, I want to create a page for each category.

Now my code looks like this:

  • ./src/components/Category01.vue file:
<template>
  ...
  ...
</template>

<static-query>
query {
  allPosts(filter: { Category: { in: ["Category01"] }})  {
    edges {
      node {
        id
        Category
        Title
      }
    }
  }
}
</static-query>

<script>
export default {
    name: "Category01",
};
</script>
  • ./src/components/Category02.vue file:
<template>
  ...
  ...
</template>

<static-query>
query {
  allPosts(filter: { Category: { in: ["Category02"] }})  {
    edges {
      node {
        id
        Category
        Title
      }
    }
  }
}
</static-query>

<script>
export default {
    name: "Category02",
};
</script>

All are the same except for the different category name.

Is there a better way to create a page for each category?

Thank you!

CearaWeir
  • 33
  • 2

1 Answers1

1

You can use the Pages API to create your Category pages dynamically.

You'll only need 1 CategoryPage.vue file in the templates directory, in the template file filter the current category by the category name:

gridesome.server.js

module.exports = function(api) {
  api.createPages(async ({ graphql, createPage }) => {
    const { data } = await graphql(`
      {
        allPosts {
          edges {
            node {
              id
              Category
              Title
            }
          }
        }
      }
    `);

    data.allPosts.edges.forEach(({ node }) => {
        createPage({
          path: `/PATH-TO-POSTS/${node.id}`,
          component: "./src/templates/CategoryPage.vue",
          context: {
            categoryName: node.Category // this will be used as a query variable in CategoryPage.vue
          }
        });
    });
  }
}

templates/CategoryPage.vue:

<page-query>
 query Vid ($categoryName: String!){
 videos: allPosts (filter: {Category: {eq: $categoryName}}) {
    edges {
      node {
        Category
      }
    }
  }
}
 </page-query>

Hope this helps!

Shaya Ulman
  • 1,299
  • 1
  • 12
  • 24