【问题标题】:I am using gridsome, is there a better way to create a page for each category?我正在使用 gridsome,有没有更好的方法来为每个类别创建一个页面?
【发布时间】:2020-07-17 11:34:16
【问题描述】:

我使用gridsome-source-mysql插件从MySQL获取数据。

文章有50多个类别,我想为每个类别创建一个页面。

现在我的代码如下所示:

  • ./src/components/Category01.vue文件:
<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文件:
<template>
  ...
  ...
</template>

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

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

除了类别名称不同之外,其他都是相同的。

有没有更好的方法来为每个类别创建一个页面?

谢谢!

【问题讨论】:

    标签: vue.js gridsome


    【解决方案1】:

    您可以使用Pages API 动态创建您的Category 页面。

    您只需要templates目录中的1个CategoryPage.vue文件,在模板文件中按类别名称过滤当前类别:

    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
              }
            });
        });
      }
    }
    

    模板/CategoryPage.vue:

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2010-11-08
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多