Skip to content
On this page

TypeScript开发实用技巧

1、创建dom

ts
interface IStyle {
  [key: string]: string | number
}

export default class CustomElement {
  tag: string = 'div'
  el: HTMLElement | null = null
  style: IStyle = {}
  styleUpdateTimeHandler: number | null = null

  constructor(tag = 'div') {
    this.setTag(tag)
  }

  setTag(tag: string = 'div') {
    this.tag = tag
    this.el = document.createElement(tag)
  }

  setStyle(style: IStyle) {
    this.style = {
      ...this.style,
      ...style
    }
    this.updateStyle()
  }

  updateStyle() {
    if (this.styleUpdateTimeHandler) {
      clearTimeout(this.styleUpdateTimeHandler) 
    }
    // @ts-ignore
    this.styleUpdateTimeHandler = setTimeout(() => {
      let styleStr = ''
      if (this.el) {
        Object.keys(this.style).forEach(key => {
          styleStr += `${key}: ${this.style[key]};`
        })
        this.el.setAttribute('style', styleStr)
      }
    }, 100)
  }

  appendChild(el: CustomElement) {
    if (el.el) {
      this.el?.appendChild(el.el)
    }
  }

  removeChild(el: CustomElement) {
    if (el.el) {
      this.el?.removeChild(el.el)
    }
  }

  remove() {
    this.el?.parentNode?.removeChild(this.el)
  }

  appendTo(el: HTMLElement) {
    if (this.el) {
      el.appendChild(this.el)
    }
  }
}

使用

ts
mounted() {
  const el = new CustomElement()
  el.setStyle({
    width: '100px',
    height: '100px',
    background: 'red'
  })
  el.appendTo(this.$el)
}

Released under the MIT License.