Skip to content

Commit bc389e6

Browse files
committed
Update index.ts
1 parent 26b8b9f commit bc389e6

1 file changed

Lines changed: 41 additions & 15 deletions

File tree

docs/.vitepress/theme/index.ts

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import DefaultTheme from 'vitepress/theme'
2-
import { h, onMounted, watch } from 'vue'
2+
import { h, onMounted, watch, nextTick } from 'vue'
33
import { useRoute } from 'vitepress'
44

55
export default {
@@ -10,17 +10,31 @@ export default {
1010
onMounted(() => {
1111
// 首页不显示评论
1212
if (route.path !== '/') {
13-
loadGiscus()
13+
nextTick(() => {
14+
loadGiscus()
15+
})
1416
}
1517
})
1618

1719
// 监听路由变化
1820
watch(() => route.path, (newPath) => {
21+
// 清除旧的评论区
22+
const oldContainer = document.querySelector('.giscus-container')
23+
if (oldContainer) {
24+
oldContainer.remove()
25+
}
26+
27+
// 清除旧的脚本
28+
const oldScript = document.querySelector('script[src*="giscus.app/client.js"]')
29+
if (oldScript) {
30+
oldScript.remove()
31+
}
32+
33+
// 新页面加载评论
1934
if (newPath !== '/') {
20-
// 延迟加载,确保DOM已经更新
21-
setTimeout(() => {
35+
nextTick(() => {
2236
loadGiscus()
23-
}, 100)
37+
})
2438
}
2539
})
2640

@@ -30,33 +44,45 @@ export default {
3044

3145
// 加载giscus脚本
3246
function loadGiscus() {
33-
// 检查是否已经加载了giscus脚本
34-
if (document.querySelector('script[src*="giscus.app/client.js"]')) {
35-
return
36-
}
37-
3847
// 创建样式
3948
const style = document.createElement('style')
4049
style.textContent = `
4150
.giscus-container {
4251
max-width: 740px;
4352
margin: 0 auto;
4453
padding: 0 1.5rem;
54+
margin-top: 2rem;
4555
}
4656
.giscus-frame {
4757
width: 100% !important;
4858
}
59+
.VPContent .content {
60+
max-width: 740px;
61+
margin: 0 auto;
62+
padding: 0 1.5rem;
63+
}
4964
`
50-
document.head.appendChild(style)
65+
66+
// 检查是否已有样式,如有则更新,无则添加
67+
const existingStyle = document.querySelector('style[data-giscus-style]')
68+
if (existingStyle) {
69+
existingStyle.textContent = style.textContent
70+
} else {
71+
style.setAttribute('data-giscus-style', 'true')
72+
document.head.appendChild(style)
73+
}
5174

5275
// 创建giscus容器
5376
const container = document.createElement('div')
5477
container.className = 'giscus-container'
5578

56-
// 查找合适的位置插入容器(在文章内容下方)
57-
const contentContainer = document.querySelector('.VPContent') || document.querySelector('.content')
58-
if (contentContainer) {
59-
contentContainer.appendChild(container)
79+
// 查找合适的位置插入容器(在文章内容下方,靠近文章末尾)
80+
const articleContainer = document.querySelector('.VPContent .content') ||
81+
document.querySelector('.content') ||
82+
document.querySelector('.VPContent')
83+
84+
if (articleContainer) {
85+
articleContainer.appendChild(container)
6086
} else {
6187
// 如果找不到容器,就添加到body末尾
6288
document.body.appendChild(container)

0 commit comments

Comments
 (0)