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(defineModel): correct update with multiple changes in same tick #11430

Merged
merged 2 commits into from
Jul 24, 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
25 changes: 15 additions & 10 deletions packages/runtime-core/__tests__/helpers/useModel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -614,32 +614,31 @@ describe('useModel', () => {
})

test('set no change value', async () => {
let changeChildMsg: (() => void) | null = null
let changeChildMsg!: (val: string) => void

const compRender = vi.fn()
const setValue = vi.fn()
const Comp = defineComponent({
props: ['msg'],
emits: ['update:msg'],
setup(props) {
const childMsg = useModel(props, 'msg')
changeChildMsg = () => {
childMsg.value = childMsg.value
}
changeChildMsg = (val: string) => (childMsg.value = val)
return () => {
return childMsg.value
}
},
})

const msg = ref('HI')
const defaultVal = 'defaultVal'
const msg = ref(defaultVal)
const Parent = defineComponent({
setup() {
return () =>
h(Comp, {
msg: msg.value,
'onUpdate:msg': val => {
msg.value = val
compRender()
setValue()
},
})
},
Expand All @@ -648,8 +647,14 @@ describe('useModel', () => {
const root = nodeOps.createElement('div')
render(h(Parent), root)

expect(compRender).toBeCalledTimes(0)
changeChildMsg!()
expect(compRender).toBeCalledTimes(0)
expect(setValue).toBeCalledTimes(0)

changeChildMsg(defaultVal)
expect(setValue).toBeCalledTimes(0)

changeChildMsg('changed')
changeChildMsg(defaultVal)
expect(setValue).toBeCalledTimes(2)
expect(msg.value).toBe(defaultVal)
})
})
7 changes: 5 additions & 2 deletions packages/runtime-core/src/helpers/useModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function useModel(

const res = customRef((track, trigger) => {
let localValue: any
let prevSetValue: any
let prevSetValue: any = EMPTY_OBJ
let prevEmittedValue: any

watchSyncEffect(() => {
Expand All @@ -51,7 +51,10 @@ export function useModel(
},

set(value) {
if (!hasChanged(value, localValue)) {
if (
!hasChanged(value, localValue) &&
!(prevSetValue !== EMPTY_OBJ && hasChanged(value, prevSetValue))
jh-leong marked this conversation as resolved.
Show resolved Hide resolved
) {
return
}
const rawProps = i.vnode!.props
Expand Down