Skip to content

VitePress 接入 Giscus:参数、路由与单页禁用 ​

Giscus 将评论保存在 GitHub Discussions。下面使用官方 Vue 组件,将评论挂在文章末尾;仓库和分类 ID 从 Giscus 配置页取得。

安装组件 ​

sh
npm install @giscus/vue

这里使用官方 Vue 组件。已有第三方插件时先检查兼容性,迁移时避免同时加载两套评论。

主题挂载位置 ​

将下面的组件保存为 .vitepress/theme/Comments.vue。在主题入口 .vitepress/theme/index.ts 中使用 doc-after 插槽:

ts
import { h } from 'vue'
import DefaultTheme from 'vitepress/theme'
import Comments from './Comments.vue'

export default {
  extends: DefaultTheme,
  Layout: () => h(DefaultTheme.Layout, null, {
    'doc-after': () => h(Comments)
  })
}

已有自定义 Layout 时,只合并 doc-after 插槽,保留其他插槽和 enhanceApp。

Comments.vue 示例 ​

ID 必须替换为配置页生成的真实值:

vue
<script setup>
import Giscus from '@giscus/vue'
import { useData, useRoute } from 'vitepress'
const route = useRoute()
const { frontmatter, isDark } = useData()
</script>

<template>
  <ClientOnly>
    <Giscus
      v-if="frontmatter.comment !== false"
      :key="route.path"
      repo="OWNER/REPOSITORY"
      repo-id="REPLACE_REPO_ID"
      category="General"
      category-id="REPLACE_CATEGORY_ID"
      mapping="pathname"
      :theme="isDark ? 'dark' : 'light'"
      lang="zh-CN"
    />
  </ClientOnly>
</template>

路由 key 让页面切换时重建评论。pathname 映射依赖 URL,改路径前规划历史讨论如何关联;标题映射则会受文章改名影响。

获取字段 ​

在 Giscus 配置页 填公开仓库,开启 Discussions,按提示安装 Giscus GitHub App。选择讨论分类后,页面生成脚本参数,逐项对应:

配置页生成的属性Vue 组件字段
data-reporepo,格式 OWNER/REPOSITORY
data-repo-idrepo-id,替换 REPLACE_REPO_ID
data-categorycategory,替换示例 General
data-category-idcategory-id,替换 REPLACE_CATEGORY_ID

ID 不是仓库名称或访问令牌。更换仓库时,仓库与分类的 ID 一起重新生成。

单页禁用 ​

在不需要评论的页面前言加入:

yaml
---
comment: false
---

评论空白、串页或重复 ​

先打开文章 A,再从站内链接进入文章 B。mapping="pathname" 按地址路径分开讨论,:key="route.path" 在跳转时重建组件;若两页显示同一讨论,比较两页路径和实际 mapping。空白时在浏览器网络面板找 giscus iframe 请求,回配置页确认仓库和分类仍可选。不在公开站点填 Token。

禁用页的 comment: false 必须是布尔值,不加引号;该页不应生成评论 iframe。切换深色模式时,theme 的值随 isDark 在 dark/light 之间变化。

停用评论时移除挂载组件,保留 Discussions 的已有评论。迁移映射先用少量页面验证,避免创建重复讨论。

官方文档 ​

最近更新