Skip to content

Commit

Permalink
fix(custom-element): fix that boolean prop with default true can't up…
Browse files Browse the repository at this point in the history
…dated to falsy value (vuejs#12214)
  • Loading branch information
lejunyang committed Oct 18, 2024
1 parent 657603d commit b805cef
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
32 changes: 32 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,38 @@ describe('defineCustomElement', () => {
expect(e.value).toBe('hi')
})

// #12214
test('Boolean prop with default true', async () => {
const E = defineCustomElement({
props: {
foo: {
type: Boolean,
default: true,
},
},
render() {
return String(this.foo)
},
})
customElements.define('my-el-default-true', E)
container.innerHTML = `<my-el-default-true></my-el-default-true>`
const e = container.childNodes[0] as HTMLElement & { foo: any },
shadowRoot = e.shadowRoot as ShadowRoot
expect(shadowRoot.innerHTML).toBe('true')
e.foo = undefined
await nextTick()
expect(shadowRoot.innerHTML).toBe('true')
e.foo = false
await nextTick()
expect(shadowRoot.innerHTML).toBe('false')
e.foo = null
await nextTick()
expect(shadowRoot.innerHTML).toBe('null')
e.foo = ''
await nextTick()
expect(shadowRoot.innerHTML).toBe('true')
})

test('support direct setup function syntax with extra options', () => {
const E = defineCustomElement(
props => {
Expand Down
8 changes: 7 additions & 1 deletion packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ export class VueElement
private _childStyles?: Map<string, HTMLStyleElement[]>
private _ob?: MutationObserver | null = null
private _slots?: Record<string, Node[]>
private _skipRemoveSet = new Set<string>()

constructor(
/**
Expand Down Expand Up @@ -466,8 +467,12 @@ export class VueElement
protected _setAttr(key: string): void {
if (key.startsWith('data-v-')) return
const has = this.hasAttribute(key)
let value = has ? this.getAttribute(key) : REMOVAL
const camelKey = camelize(key)
let value = has ? this.getAttribute(key) : REMOVAL
if (this._skipRemoveSet.has(camelKey)) {
if (value === REMOVAL) return
else this._skipRemoveSet.delete(camelKey)
}
if (has && this._numberProps && this._numberProps[camelKey]) {
value = toNumber(value)
}
Expand Down Expand Up @@ -510,6 +515,7 @@ export class VueElement
} else if (typeof val === 'string' || typeof val === 'number') {
this.setAttribute(hyphenate(key), val + '')
} else if (!val) {
this._skipRemoveSet.add(key)
this.removeAttribute(hyphenate(key))
}
}
Expand Down

0 comments on commit b805cef

Please sign in to comment.