Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(custom-element): avoid premature disconnection of MutationObserver when custom elements are moved #10613

Merged
merged 3 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type Ref,
type VueElement,
createApp,
defineAsyncComponent,
defineComponent,
defineCustomElement,
Expand Down Expand Up @@ -60,6 +61,54 @@ describe('defineCustomElement', () => {
expect(e.shadowRoot!.innerHTML).toBe('')
})

// #10610
test('When elements move, avoid prematurely disconnecting MutationObserver', async () => {
const CustomInput = defineCustomElement({
props: ['value'],
emits: ['update'],
setup(props, { emit }) {
return () =>
h('input', {
type: 'number',
value: props.value,
onInput: (e: InputEvent) => {
const num = (e.target! as HTMLInputElement).valueAsNumber
emit('update', Number.isNaN(num) ? null : num)
},
})
},
})
customElements.define('my-el-input', CustomInput)
const num = ref('12')
const containerComp = defineComponent({
setup() {
return () => {
return h('div', [
h('my-el-input', {
value: num.value,
onUpdate: ($event: CustomEvent) => {
num.value = $event.detail[0]
},
}),
h('div', { id: 'move' }),
])
}
},
})
const app = createApp(containerComp)
app.mount(container)
const myInputEl = container.querySelector('my-el-input')!
const inputEl = myInputEl.shadowRoot!.querySelector('input')!
await nextTick()
expect(inputEl.value).toBe('12')
const moveEl = container.querySelector('#move')!
moveEl.append(myInputEl)
await nextTick()
myInputEl.removeAttribute('value')
await nextTick()
expect(inputEl.value).toBe('')
})

test('should not unmount on move', async () => {
container.innerHTML = `<div><my-element></my-element></div>`
const e = container.childNodes[0].childNodes[0] as VueElement
Expand Down
8 changes: 4 additions & 4 deletions packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,12 @@ export class VueElement extends BaseClass {

disconnectedCallback() {
this._connected = false
if (this._ob) {
this._ob.disconnect()
this._ob = null
}
nextTick(() => {
if (!this._connected) {
if (this._ob) {
this._ob.disconnect()
this._ob = null
}
render(null, this.shadowRoot!)
this._instance = null
}
Expand Down