Skip to content

Commit

Permalink
feat(runtime-dom): support specifying shadow dom styles in defineCust…
Browse files Browse the repository at this point in the history
…omElement
  • Loading branch information
yyx990803 committed Jul 22, 2021
1 parent f0ca233 commit a7fa4ac
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
16 changes: 16 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,4 +274,20 @@ describe('defineCustomElement', () => {
expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
})
})

describe('styles', () => {
test('should attach styles to shadow dom', () => {
const Foo = defineCustomElement({
styles: [`div { color: red; }`],
render() {
return h('div', 'hello')
}
})
customElements.define('my-el-with-styles', Foo)
container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
const el = container.childNodes[0] as VueElement
const style = el.shadowRoot?.querySelector('style')!
expect(style.textContent).toBe(`div { color: red; }`)
})
})
})
19 changes: 13 additions & 6 deletions packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
Component,
ComponentOptionsMixin,
ComponentOptionsWithArrayProps,
ComponentOptionsWithObjectProps,
Expand All @@ -18,7 +17,8 @@ import {
createVNode,
defineComponent,
nextTick,
warn
warn,
ComponentOptions
} from '@vue/runtime-core'
import { camelize, extend, hyphenate, isArray, toNumber } from '@vue/shared'
import { hydrate, render } from '.'
Expand Down Expand Up @@ -60,7 +60,7 @@ export function defineCustomElement<
Extends,
E,
EE
>
> & { styles?: string[] }
): VueElementConstructor<Props>

// overload 3: object format with array props declaration
Expand All @@ -85,7 +85,7 @@ export function defineCustomElement<
Extends,
E,
EE
>
> & { styles?: string[] }
): VueElementConstructor<{ [K in PropNames]: any }>

// overload 4: object format with object props declaration
Expand All @@ -110,7 +110,7 @@ export function defineCustomElement<
Extends,
E,
EE
>
> & { styles?: string[] }
): VueElementConstructor<ExtractPropTypes<PropsOptions>>

// overload 5: defining a custom element from the returned value of
Expand Down Expand Up @@ -176,7 +176,7 @@ export class VueElement extends BaseClass {
_connected = false

constructor(
private _def: Component,
private _def: ComponentOptions & { styles?: string[] },
private _attrKeys: string[],
private _propKeys: string[],
hydrate?: RootHydrateFunction
Expand All @@ -192,6 +192,13 @@ export class VueElement extends BaseClass {
)
}
this.attachShadow({ mode: 'open' })
if (_def.styles) {
_def.styles.forEach(css => {
const s = document.createElement('style')
s.textContent = css
this.shadowRoot!.appendChild(s)
})
}
}
}

Expand Down

0 comments on commit a7fa4ac

Please sign in to comment.