自定义 Web Components 指南#
使用 independoc,无需引入 React 或任何前端打包工具,即可直接在 Markdown 中嵌入团队专属的交互式组件。
3 步添加自定义组件#
在
static/下放置原生 JS Custom Element按照 HTML 规范,自定义元素标签名必须包含连字符(
-)。static/hello-counter.jsclass HelloCounter extends HTMLElement { connectedCallback() { if (this._initialized) return; this._initialized = true; const initial = Number(this.getAttribute('start') || 0); let count = Number.isFinite(initial) ? initial : 0; const label = this.getAttribute('label') || 'Clicks'; const resetLabel = this.getAttribute('reset-label') || 'Reset'; this.innerHTML = ''; const wrap = document.createElement('div'); wrap.className = 'hc-wrap'; const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'nd-icon-btn hc-btn'; const resetBtn = document.createElement('button'); resetBtn.type = 'button'; resetBtn.className = 'nd-icon-btn hc-reset'; resetBtn.textContent = resetLabel; const update = () => { btn.textContent = `${label}: ${count}`; }; btn.addEventListener('click', () => { count += 1; update(); }); resetBtn.addEventListener('click', () => { count = Number.isFinite(initial) ? initial : 0; update(); }); update(); wrap.append(btn, resetBtn); this.append(wrap); } } if (!customElements.get('hello-counter')) { customElements.define('hello-counter', HelloCounter); }在
independoc.config.json中注册脚本independoc.config.json{ "customScripts": ["/hello-counter.js"] }直接在 Markdown 中使用
markdown<hello-counter start="1" label="点击次数" reset-label="重置"> <p>在禁用 JavaScript 的环境中,这段回退文本会原样显示。</p> </hello-counter>
在线演示(<hello-counter>)#
本官方文档站点已注册 static/hello-counter.js,下方即为实际运行的自定义组件。您可以点击按钮测试计数与重置效果。
在禁用 JavaScript 的环境中,这段回退文本会原样显示。