怎么在html文件中使用组件

使用的知识是 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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值