webComponents

组件是前端的发展方向,Web Components即浏览器的原生组件,相比第三方框架,原生组件简单直接,符合直觉,不用加载任何外部模块,代码量小。

实现这样一个效果

 

 

 简单示例demo如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
 <!-- 使用组件 --> <my-info src="./images/cc.png" name="小李" email="xxx.163.com"></my-info> <hr/> <my-info src="./images/aa.png" name="小王" email="xxx.qq.com"></my-info> <template id="my-info"> <!-- style里定component样式 , template里面写模板--> <style> .info { display: flex; justify-items: center; } img { width: 100px; height: 200px; margin-right: 50px; } </style> <div class="info"> <img class="img"/> <div> <p class="name"></p> <p class="email"></p> <button onclick="query">follow</button> </div> </div> </template> <script type="module"> import './myInfo.js' </script> </body> </html>

 引入myInfo.js

class myInfo extends HTMLElement {
  constructor() {
    super()
    const content = document.getElementById('my-info')
    const item = content.content.cloneNode(true)
    const imgObj = item.querySelector('.img')
    const nameObj = item.querySelector('.name')
    const emailObj = item.querySelector('.email')
    imgObj.src=this.getAttribute('src')
    nameObj.innerText = this.getAttribute('name')
    emailObj.innerText = this.getAttribute('email')
    this.appendChild(item)
  }
}

// 定义组件名称
window.customElements.define('my-info', myInfo)

本示例是简单演示,更多细节还请继续深入

posted @ 2022-02-14 10:01  夏之轩语  阅读(470)  评论(0编辑  收藏  举报