原生代码实现:
<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