Web Components

最简 Radio

最简的自定义Radio,只是封装了label:
封装前:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="radio" name="lan" checked  value="react" id="react">
    <label for="react">react</label> 
    <input type="radio" name="lan"   value="vue" id="vue">
    <label for="vue">vue</label> 

    <script>
        var $input =document.querySelector("input[name='lan'][checked]");
        console.log($input.checked);
    </script>
    </script>
</body>
</html>

封装后:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DC-RADIO</title>
    <script src="./dc-radio.js" defer></script>
  </head>
  <body>
    <dc-radio name="lan" value="react" disabled>react</dc-radio>
    <dc-radio name="lan" value="vue" checked>vue</dc-radio>
    <dc-radio name="lan" value="ng">ng</dc-radio>
    <button onclick="handleClick()">TEST</button>
    <script>
      function handleClick() {
        const $radio = document.querySelector("dc-radio[name='lan'][checked]");
        // $radio.checked = true;
        console.log($radio.value);
      }
    </script>
  </body>
</html>

Radio 实现:

/**
 * dc-radio
 *
 * @description A radio button component
 * 
 * 1. name属性相同的radio按钮,会被认为是一组,只能选择一个:添加事件监听change事件,其它Radio checked=false
 * (input checked -> radio checked)
 * (radio checked -> input checked)
 *
 */
class DCRadio extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = `
            <style>
              
            </style>
            <label for="radio">
                <input type="radio" id="radio"/>
                <slot></slot>
            </label>      
        `
        this.$input = this.shadowRoot.querySelector('input')
    }

    get value() {
        return this.getAttribute('value') || this.textContent
    }

    get name() {
        return this.getAttribute('name')
    }

    set name(value) {
        this.setAttribute('name', value)
    }

    set disabled(value) {
        this.toggleAttribute('disabled', value)
    }

    set checked(value) {
        this.toggleAttribute('checked', value)

    }

    static get observedAttributes() {
        return ['checked', 'disabled']
    }

    connectedCallback() {
        this.$input.addEventListener('change', () => {
            this.checked = true
            this.dispatchEvent(new CustomEvent('change'))
        })
    }


    attributeChangedCallback(name, oldValue, newValue) {
        this.$input[name] = newValue !== null

        if (name === 'checked' && newValue !== null) {
            document.querySelectorAll(`dc-radio[name=${this.name}][checked]`).forEach(radio => {
                if (radio !== this) {
                    radio.checked = false
                }
            })
        }
    }
}

customElements.define('dc-radio', DCRadio);
  1. 定义自定义元素:通过继承HTMLElement创建自定义元素,通过customElements.define()定义元素标签;
  2. 定制元素内容:通过shadowDom来承载元素内容,包括样式和结构;
  3. 读取属性:由于属性不是原生标签的属性,所以需要通过 getAttribute() 获取属性值;
  4. 监听属性变化:通过observedAttributes()监听属性变化,当属性改变调用attributeChangedCallback()方法;
  5. 子元素和父元素通信:子元素通过dispatchEvent()向父元素发送消息,父元素通过监听相应事件接收消息。

有样式的 Radio

class DCStyledRadio extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = `
            <style>
                :host {
                    display: inline-flex;
                    align-items: center;
                    gap: 8px;
                }
                
                input {
                    appearance: none;
                    margin: 0;
                    width: 16px;
                    height: 16px;
                    border-radius: 50%;
                    border: 1px solid #d9d9d9;
                    background-color: #fff;
                }
                
                input:checked {
                    border: 5px solid #1677ff;
                }

                input:disabled {
                    opacity: 0.6;
                    cursor: default;
                }

                input:not(:disabled):is(:hover) {
                    border-color: #1677ff;
                    cursor: pointer;
                }

                label {
                    cursor: pointer;
                }

                :disabled+label {
                    cursor: default;
                }
            </style>
            <input type="radio" id="radio"/>
            <label for="radio">
                <slot></slot>
            </label>      
        `
        this.$input = this.shadowRoot.querySelector('input')
    }

    get value() {
        return this.getAttribute('value') || this.textContent
    }

    get name() {
        return this.getAttribute('name')
    }

    set name(value) {
        this.setAttribute('name', value)
    }

    set disabled(value) {
        this.toggleAttribute('disabled', value)
    }

    set checked(value) {
        this.toggleAttribute('checked', value)

    }

    static get observedAttributes() {
        return ['checked', 'disabled']
    }

    connectedCallback() {
        this.$input.addEventListener('change', () => {
            this.checked = true
            this.dispatchEvent(new CustomEvent('change'))
        })
    }


    attributeChangedCallback(name, oldValue, newValue) {
        this.$input[name] = newValue !== null

        if (name === 'checked' && newValue !== null) {
            document.querySelectorAll(`dc-styled-radio[name=${this.name}][checked]`).forEach(radio => {
                if (radio !== this) {
                    radio.checked = false
                }
            })
        }
    }
}

customElements.define('dc-styled-radio', DCStyledRadio);

Radio Group

嵌套在RadioGroup下的Radio是同一组,value属性标明当前选中的Radio。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DC-RADIO-GROUP</title>
    <script src="./dc-radio.js" defer></script>
    <script src="./dc-radio-group.js" defer></script>
  </head>
  <body>
    <dc-radio-group name="lan" value="vue">
      <dc-radio value="react">react</dc-radio>
      <dc-radio value="vue">vue</dc-radio>
      <dc-radio value="ng">ng</dc-radio>
    </dc-radio-group>
    <button onclick="handleClick()">TEST</button>
    <script>
      function handleClick() {
        const $radioGroup = document.querySelector("dc-radio-group");
        $radioGroup.addEventListener("change", (e) => {
          console.log(1111, e);
        });
        // $radio.checked = true;
        console.log($radioGroup.value);
      }
    </script>
  </body>
</html>

RadioGroup 实现

/**
 * 1. 根据 name 属性,设置 dc-radio 的 name 属性
 * 2. 根据 value 属性,设置 dc-radio 的 checked 属性
 */
class DCRadioGroup extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = `
      <style>
       
      </style>
      <slot></slot>
      `
    }

    get name() {
        return this.getAttribute("name");
    }

    get value() {
        return this.getAttribute("value")
    }

    set value(val) {
        this.setAttribute("value", val);
    }
    static get observedAttributes() {
        return ["value"];
    }
    connectedCallback() {
        this.querySelectorAll('dc-radio').forEach(radio => {
            radio.name = this.name
            radio.addEventListener('change', () => {
                this.value = radio.value
                this.dispatchEvent(new CustomEvent('change', {
                    detail: {
                        value: radio.value
                    }
                }))
            })
        })
    }

    attributeChangedCallback(name, oldValue, newValue) {
        this.querySelectorAll('dc-radio').forEach(radio => {
            radio.checked = radio.value === newValue
        })
    }
}

customElements.define("dc-radio-group", DCRadioGroup);

知识点

  • 自定义属性:不能像自有属性(如onclick等)那样直接通过点语法(如element.data - custom)在大多数浏览器中访问。只能通过getAttribute方法来获取其值。
  • 脚本执行顺序:加 defer。
  • 伪元素: ::part() 参考 xy-ui。

参考

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容

  • 前言:这周完成了两场技术分享会,下周还有一场,就完成了这阶段的一个重大任务。分享会是关于 TS 的,我这两场分享会...
    CondorHero阅读 991评论 0 2
  • 现在的前端开发基本离不开 React、Vue 这两个框架的支撑,而这两个框架下面又衍生出了许多定义组件库: 这些组...
    wan_c1121阅读 1,092评论 1 2
  • 组件化是前端工程化重要的一环,UI 和 交互(或逻辑)的复用极大的提高开发效率以及减少代码冗余。 目前开源的组件库...
    一蓑烟雨任平生_cui阅读 4,528评论 0 4
  • 简单例子 定义 Web Components 是一套不同的技术,允许您创建可重用的定制元素(它们的功能封装在您的代...
    copyLeft阅读 287评论 0 1
  • Web Components 首先来了解下 Web Components 的基本概念, Web Component...
    涅槃快乐是金阅读 759评论 0 3