|
| 1 | +//theme/Layout/comment |
| 2 | +<template> |
| 3 | + <div class="content-container"></div> |
| 4 | +</template> |
| 5 | + |
| 6 | +<script setup lang="ts"> |
| 7 | +import { watch, nextTick, onMounted, ref } from 'vue' |
| 8 | +import 'gitalk/dist/gitalk.css' //引入 gitalk 的 css 样式 |
| 9 | +import Gitalk from 'gitalk' |
| 10 | +import { useRouter } from 'vitepress' |
| 11 | +import { inBrowser } from 'vitepress' |
| 12 | +
|
| 13 | +let { route } = useRouter() // 页面路由对象 |
| 14 | +const options = { |
| 15 | + id: route.data.title, // 可选,推荐设置为页面标题,因为会作为标签传给Github issues,且issues标签有长度限制。 |
| 16 | + owner: 'lhuans', // GitHub repository 所有者 |
| 17 | + repo: 'https://github.com/lhuans/docs', // GitHub repository |
| 18 | + clientID: 'Ov23li4JzHJFiyJQxL24', // 自己的clientID |
| 19 | + clientSecret: '255695afc71cdd6ad613655866646311f5a763ec', // 自己的clientSecret |
| 20 | + admin: ['lhuans'], // GitHub repository 所有者 |
| 21 | + labels: ['Gitalk'], // GitHub issue 的标签 |
| 22 | + createIssueManually: false //如果当前页面没有相应的 isssue 且登录的用户属于 admin,则会自动创建 issue。如果设置为 true,则显示一个初始化页面,创建 issue 需要点击 init 按钮。 |
| 23 | +} |
| 24 | +const init = () => { |
| 25 | + //如果在浏览器环境 |
| 26 | + if (inBrowser) { |
| 27 | + watch( |
| 28 | + () => route.path, // 监听路由变化,重新挂载评论组件 |
| 29 | + () => { |
| 30 | + nextTick(() => { |
| 31 | + if (typeof window !== undefined) { |
| 32 | + const containerElement = |
| 33 | + document.querySelector('.content-container') |
| 34 | + if (containerElement) { |
| 35 | + const contentElement = document.getElementById( |
| 36 | + 'gitalk-page-container' |
| 37 | + ) |
| 38 | + if (contentElement) { |
| 39 | + //判断是否已有评论组件节点,有则删除,重新创建。 |
| 40 | + contentElement.removeChild(containerElement) |
| 41 | + } |
| 42 | + const wrap = document.createElement('div') |
| 43 | + wrap.setAttribute('id', 'gitalk-page-container') |
| 44 | + const comment = document.querySelector( |
| 45 | + '.content-container' |
| 46 | + ) as HTMLElement |
| 47 | + comment.appendChild(wrap) // 把组件加入到想加载的地方 |
| 48 | + } |
| 49 | + const gitTalk = new Gitalk(options) |
| 50 | + gitTalk.render('gitalk-page-container') |
| 51 | + } |
| 52 | + }) |
| 53 | + }, |
| 54 | + { immediate: true } |
| 55 | + ) |
| 56 | + } |
| 57 | +} |
| 58 | +onMounted(() => { |
| 59 | + init() |
| 60 | +}) |
| 61 | +</script> |
0 commit comments