原生编写组件 Web Components

原生编写组件 Web Components,第1张

 

 

 原生代码实现:

<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

原生编写组件 Web Components

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/1006833.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存