示例工程 21-web-components

21-web-components/03-light-dom/main.js

javascript · 1.2 KB

运行:21 · 无 Shadow DOM 的计数器

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— 无 Shadow DOM 的计数器模型
export function createCounterModel(initial = 0, step = 1) {
  let value = initial;
  let stride = step;
  return {
    inc() {
      value += stride;
      return value;
    },
    dec() {
      value -= stride;
      return value;
    },
    setStep(next) {
      stride = next;
    },
    get value() {
      return value;
    },
  };
}
 
export function run(log = console.log) {
  if (typeof document === 'undefined') {
    throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
  }
  const el = document.querySelector('x-light-counter');
  if (!el) throw new Error('未找到 <x-light-counter>');
 
  log(`shadowRoot 是否为 null:${el.shadowRoot === null}`);
  log(`light DOM 子元素数:${el.children.length}`);
  el.querySelector('[data-action="inc"]').click();
  el.querySelector('[data-action="inc"]').click();
  log(`点击两次后:${el.querySelector('[data-value]').textContent}`);
  log('要点:不用 Shadow DOM 也能封装行为,但样式与内部结构对外可见。');
  return { hasShadow: el.shadowRoot !== null, text: el.querySelector('[data-value]').textContent };
}