Gridsome开发分类模板时提示String!类型变量未提供报错如何解决?
问题根因
你用错了Gridsome的查询类型:
<static-query>是全局静态查询,构建时全局仅执行一次,不支持接收页面context传入的动态参数- 只有
<page-query>(页面查询)是专门给模板页面使用的,可以读取gridsome.server.js中createPage传入的context参数
修复步骤
1. 修改分类模板的查询类型
把JobsCategoryListSection.vue中的<static-query>改为<page-query>,同时补全变量的非空标识匹配后端类型要求:
<page-query> query ($category: String!) { django { jobOfferList(category_Icontains: $category) { edges { node { id description company category active createdAt title } } } } } </page-query>
2. 调整模板中的数据读取路径
page-query的查询结果挂载在$page对象上,所以模板部分遍历数据要修改为:
<template> <section class="section"> <h1 class="title">分类:{{ $context.category }} 的岗位列表</h1> <div class="columns is-multiline"> <JobOfferCard v-for="(edge, index) in $page.django.jobOfferList.edges" :key="index" :content="edge.node" /> </div> </section> </template> <script> import JobOfferCard from "@/components/JobOfferCard.vue"; export default { name: "JobsCategoryListSection", components: { JobOfferCard }, }; </script>
3. 优化分类页生成逻辑(必做,避免重复生成页面报错)
你之前直接遍历岗位列表生成分类页,同一个分类下有多个岗位时会重复创建同路径页面,需要先对分类去重再生成,修改gridsome.server.js中的分类页生成代码:
// 先提取所有去重后的分类 const categories = [...new Set(data.django.jobOfferList.edges.map(({ node }) => node.category))] // 遍历生成分类页 categories.forEach(category => { createPage({ path: `/${category}`, component: "./src/templates/JobsCategoryListSection.vue", context: { category: category, }, }); })
内容的提问来源于stack exchange,提问作者Arka-cell
相关产品推荐
相关产品推荐

