|
| 1 | +<script setup lang="ts"> |
| 2 | +import { onMounted, watch, ref } from "vue"; |
| 3 | +import { useData, useRoute } from "vitepress"; |
| 4 | +
|
| 5 | +const { isDark } = useData(); |
| 6 | +const route = useRoute(); |
| 7 | +const container = ref<HTMLElement>(); |
| 8 | +
|
| 9 | +const GISCUS_REPO = "fonghehe/blog"; |
| 10 | +const GISCUS_REPO_ID = "MDEwOlJlcG9zaXRvcnkyMTUxOTg3MTQ="; |
| 11 | +const GISCUS_CATEGORY = "Announcements"; |
| 12 | +const GISCUS_CATEGORY_ID = "DIC_kwDODNOr-s4C8kR_"; |
| 13 | +
|
| 14 | +function loadGiscus() { |
| 15 | + if (!container.value) return; |
| 16 | + container.value.innerHTML = ""; |
| 17 | +
|
| 18 | + const script = document.createElement("script"); |
| 19 | + script.src = "https://giscus.app/client.js"; |
| 20 | + script.setAttribute("data-repo", GISCUS_REPO); |
| 21 | + script.setAttribute("data-repo-id", GISCUS_REPO_ID); |
| 22 | + script.setAttribute("data-category", GISCUS_CATEGORY); |
| 23 | + script.setAttribute("data-category-id", GISCUS_CATEGORY_ID); |
| 24 | + script.setAttribute("data-mapping", "pathname"); |
| 25 | + script.setAttribute("data-strict", "0"); |
| 26 | + script.setAttribute("data-reactions-enabled", "1"); |
| 27 | + script.setAttribute("data-emit-metadata", "0"); |
| 28 | + script.setAttribute("data-input-position", "top"); |
| 29 | + script.setAttribute("data-theme", isDark.value ? "dark" : "light"); |
| 30 | + script.setAttribute("data-lang", "zh-CN"); |
| 31 | + script.setAttribute("data-loading", "lazy"); |
| 32 | + script.crossOrigin = "anonymous"; |
| 33 | + script.async = true; |
| 34 | + container.value.appendChild(script); |
| 35 | +} |
| 36 | +
|
| 37 | +onMounted(loadGiscus); |
| 38 | +
|
| 39 | +// 路由切换时重新加载(SPA 导航) |
| 40 | +watch(() => route.path, loadGiscus); |
| 41 | +
|
| 42 | +// 切换深色/浅色主题时同步通知 giscus iframe |
| 43 | +watch(isDark, (dark) => { |
| 44 | + const iframe = container.value?.querySelector<HTMLIFrameElement>( |
| 45 | + "iframe.giscus-frame", |
| 46 | + ); |
| 47 | + if (iframe) { |
| 48 | + iframe.contentWindow?.postMessage( |
| 49 | + { giscus: { setConfig: { theme: dark ? "dark" : "light" } } }, |
| 50 | + "https://giscus.app", |
| 51 | + ); |
| 52 | + } |
| 53 | +}); |
| 54 | +</script> |
| 55 | + |
| 56 | +<template> |
| 57 | + <div ref="container" class="giscus-wrapper" /> |
| 58 | +</template> |
| 59 | + |
| 60 | +<style scoped> |
| 61 | +.giscus-wrapper { |
| 62 | + margin-top: 3rem; |
| 63 | + padding-top: 2rem; |
| 64 | + border-top: 1px solid var(--vp-c-divider); |
| 65 | +} |
| 66 | +</style> |
0 commit comments