原生代码实现:
<template id="userCardTemplate"> <style>...</style> <img > <div > <p ></p> <p ></p> <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="http://www.kaotop.com/file/tupian/20220519/kristy.png" name="User Name" email="[email protected]" ></user-card>参考链接:https://www.ruanyifeng.com/blog/2019/08/web_components.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)