Skip to content

Commit

Permalink
feat(runtime-dom): support passing initial props to custom element co…
Browse files Browse the repository at this point in the history
…nstructor
  • Loading branch information
yyx990803 committed Jul 22, 2021
1 parent 7a7e1d8 commit 5b76843
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 12 deletions.
14 changes: 11 additions & 3 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Expand Up @@ -17,7 +17,15 @@ describe('defineCustomElement', () => {

describe('mounting/unmount', () => {
const E = defineCustomElement({
render: () => h('div', 'hello')
props: {
msg: {
type: String,
default: 'hello'
}
},
render() {
return h('div', this.msg)
}
})
customElements.define('my-element', E)

Expand All @@ -30,13 +38,13 @@ describe('defineCustomElement', () => {
})

test('should work w/ manual instantiation', () => {
const e = new E()
const e = new E({ msg: 'inline' })
// should lazy init
expect(e._instance).toBe(null)
// should initialize on connect
container.appendChild(e)
expect(e._instance).toBeTruthy()
expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
})

test('should unmount on remove', async () => {
Expand Down
13 changes: 5 additions & 8 deletions packages/runtime-dom/src/apiCustomElement.ts
Expand Up @@ -23,8 +23,8 @@ import {
import { camelize, extend, hyphenate, isArray, toNumber } from '@vue/shared'
import { hydrate, render } from '.'

type VueElementConstructor<P = {}> = {
new (): VueElement & P
export type VueElementConstructor<P = {}> = {
new (initialProps?: Record<string, any>): VueElement & P
}

// defineCustomElement provides the same type inference as defineComponent
Expand Down Expand Up @@ -134,8 +134,8 @@ export function defineCustomElement(
static get observedAttributes() {
return attrKeys
}
constructor() {
super(Comp, attrKeys, propKeys, hydate)
constructor(initialProps?: Record<string, any>) {
super(Comp, initialProps, attrKeys, propKeys, hydate)
}
}

Expand Down Expand Up @@ -163,10 +163,6 @@ const BaseClass = (
) as typeof HTMLElement

export class VueElement extends BaseClass {
/**
* @internal
*/
_props: Record<string, any> = {}
/**
* @internal
*/
Expand All @@ -178,6 +174,7 @@ export class VueElement extends BaseClass {

constructor(
private _def: ComponentOptions & { styles?: string[] },
private _props: Record<string, any> = {},
private _attrKeys: string[],
private _propKeys: string[],
hydrate?: RootHydrateFunction
Expand Down
3 changes: 2 additions & 1 deletion packages/runtime-dom/src/index.ts
Expand Up @@ -198,7 +198,8 @@ function normalizeContainer(
export {
defineCustomElement,
defineSSRCustomElement,
VueElement
VueElement,
VueElementConstructor
} from './apiCustomElement'

// SFC CSS utilities
Expand Down

0 comments on commit 5b76843

Please sign in to comment.