refactor(widget): 简化前端配置并重构核心逻辑

移除前端配置中的 postSlug 和 avatarPrefix 参数,改为从后端接口获取
重构 CWDComments 核心类,自动推导 postSlug 等参数并异步加载服务端配置
更新文档和示例页面以反映配置变更
This commit is contained in:
anghunk
2026-01-20 10:39:48 +08:00
parent 1c0c4b5657
commit 0485b1320c
11 changed files with 149 additions and 86 deletions

View File

@@ -0,0 +1,38 @@
<template>
<div id="zcomments" ref="commentsRoot"></div>
</template>
<script setup>
import { onMounted, ref } from "vue";
const commentsRoot = ref(null);
onMounted(async () => {
if (!commentsRoot.value || typeof window === "undefined") return;
const apiBaseUrl = "https://cwd-comments-api.anghunk.workers.dev";
if (!apiBaseUrl) return;
if (!window.CWDComments) {
await new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cwd-comments.zishu.me/cwd-comments.js";
script.async = true;
script.onload = () => resolve();
script.onerror = (e) => reject(e);
document.head.appendChild(script);
}).catch(() => {});
}
if (!window.CWDComments) return;
const comments = new window.CWDComments({
el: commentsRoot.value,
apiBaseUrl,
postSlug: window.location.pathname,
});
comments.mount();
});
</script>

View File

@@ -24,6 +24,7 @@ export default defineConfig({
{ text: '快速开始', link: '/guide/getting-started' },
{ text: '后端配置', link: '/guide/backend-config' },
{ text: '前端配置', link: '/guide/frontend-config' },
{ text: '管理后台', link: '/guide/admin-panel' },
]
},
{

View File

@@ -0,0 +1,15 @@
import DefaultTheme from 'vitepress/theme'
import { h } from 'vue'
import FooterDoc from '../components/footerDoc.vue'
export default {
...DefaultTheme,
Layout() {
const Layout = DefaultTheme.Layout
return h(Layout, null, {
'doc-footer-before': () => h(FooterDoc),
})
},
}

View File

@@ -13,7 +13,6 @@
const comments = new CWDComments({
el: '#comments',
apiBaseUrl: 'https://your-api.example.com',
postSlug: window.location.origin + window.location.pathname,
});
comments.mount();
</script>
@@ -25,10 +24,11 @@
| ------------ | ----------------------- | ---- | ---------------------------------------------------------------- | ------------------------- |
| `el` | `string \| HTMLElement` | 是 | - | 挂载元素选择器或 DOM 元素 |
| `apiBaseUrl` | `string` | 是 | - | API 基础地址 |
| `postSlug` | `string` | 是 | 当前页面 URL `window.location.origin + window.location.pathname` | 文章唯一标识符 |
| `theme` | `'light' \| 'dark'` | 否 | `'light'` | 主题模式 |
| `pageSize` | `number` | 否 | `20` | 每页显示评论数 |
头像前缀、博主邮箱和标识等信息由后端接口 `/api/config/comments` 提供,无需在前端进行配置。
## 实例方法
| 方法 | 说明 |
@@ -43,7 +43,4 @@
```javascript
// 动态切换主题
comments.updateConfig({ theme: 'dark' });
// 切换文章
comments.updateConfig({ postSlug: 'another-post' });
```