wuyuedefeng / blogs

博客文章在issue中
5 stars 0 forks source link

Vue 组件渲染到shadow dom中 #102

Open wuyuedefeng opened 3 years ago

wuyuedefeng commented 3 years ago

--- 参考资料


完整实现

export default {
  mounted () {
    // 创建shadow dom
    const parentElement = this.$el.parentElement
    const fragment = document.createDocumentFragment()
    // const head = document.createElement('head')
    // fragment.appendChild(head)
    fragment.appendChild(this.$el)
    const shadowRoot = parentElement.attachShadow({ mode: 'open' })
    shadowRoot.appendChild(fragment)
    const sheet = new CSSStyleSheet()
    // 拷贝样式
    // document.querySelectorAll('head > style[type="text/css"]').forEach(style => {
    //   head.appendChild(style.cloneNode(true))
    // })
    // 拷贝样式
    document.styleSheets.forEach(stylesheet => {
      stylesheet.cssRules.forEach(rule => {
        if (rule.selectorText/* && /^(\.np--|[a-z])/i.test(rule.selectorText) */) {
          sheet.insertRule(rule.cssText)
        }
      })
    })
    shadowRoot.adoptedStyleSheets = [sheet]
    // 添加自定义新样式
    sheet.insertRule(`
      a {
        outline: 2px dashed #f3d500;
      }`, 0)
  }
}