使用的知识是 web Components
只需要一个 html 文件和一个 js 文件
方式一
在 index.html 文件中
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>web Component</title>
<script src="./comp.js"></script>
</head>
<body>
<!-- 可以复用 -->
<xiaolan-comp></xiaolan-comp>
<xiaolan-comp></xiaolan-comp>
</body>
</html>
在 comp.js 文件中
// 创建自定义元素
class Comp extends HTMLElement {
constructor () {
super()
const shaDom = this.attachShadow({ mode: "open" })
this.p = this.h('p')
this.p.innerText = '小懒'
this.p.setAttribute('style', 'width:200px;height:200px;border:1px solid black')
shaDom.appendChild(this.p)
}
h (el) {
return document.createElement(el)
}
}
// 挂载
window.customElements.define('xiaolan-comp', Comp)
方式二
使用 template 模式
在 comp.js 文件中
// 创建自定义元素
class Comp extends HTMLElement {
constructor () {
super()
const shaDom = this.attachShadow({ mode: "open" })
this.template = this.h('template')
// style 都会被隔离,不会影响外面的dom
this.template.innerHTML = `
<style>
div{
width:200px;
height:200px;
border:1px solid black;
}
</style>
<div>小懒</div>
`
// 需要克隆节点
shaDom.appendChild(this.template.content.cloneNode(true))
}
h (el) {
return document.createElement(el)
}
// 四个生命周期
// 当自定义元素第一次被挂载到文档 DOM 时被调用
connectedCallback () {
console.log('连接');
}
// 当自定义元素与文档 DOM 断开连接时被调用
disconnectedCallback () {
console.log('断开连接');
}
// 当自定义元素被移动到新文档时被调用
adoptedCallback () {
console.log('移动');
}
// 当自定义元素的一个属性被增加、移除或者更改时被调用
attributeChangedCallback () {
console.log('改变');
}
}
// 挂载
window.customElements.define('xiaolan-comp', Comp)