原生编写组件 Web Components

时间:2021-06-30 18:42:37   收藏:0   阅读:0

技术图片

 

 

 原生代码实现:

<template id="userCardTemplate">
  <style>...</style>

  <img class="image">
  <div class="container">
    <p class="name"></p>
    <p class="email"></p>
    <button class="button">Follow John</button>
  </div>
</template>
<script>
  class UserCard extends HTMLElement {
    constructor() {
      super();
    // 开启 Shadow DOM,隐藏内部代码模式
      var shadow = this.attachShadow( { mode: ‘closed‘ } );

      var templateElem = document.getElementById(‘userCardTemplate‘);
      var content = templateElem.content.cloneNode(true);
      content.querySelector(‘img‘).setAttribute(‘src‘, this.getAttribute(‘image‘));
      content.querySelector(‘.container>.name‘).innerText = this.getAttribute(‘name‘);
      content.querySelector(‘.container>.email‘).innerText = this.getAttribute(‘email‘);

      shadow.appendChild(content);
    }
  }
  window.customElements.define(‘user-card‘, UserCard);
 </script>

页面中直接使用:

<user-card
  image="https://semantic-ui.com/images/avatar2/large/kristy.png"
  name="User Name"
  email="yourmail@some-email.com"
></user-card>

参考链接:https://www.ruanyifeng.com/blog/2019/08/web_components.html

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!