Skip to content

Commit

Permalink
fix(v-model): respect checkbox true-value/false-value on initial render
Browse files Browse the repository at this point in the history
fix #2694
  • Loading branch information
yyx990803 committed Dec 1, 2020
1 parent 085bbd5 commit 48f00c0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
21 changes: 12 additions & 9 deletions packages/runtime-dom/__tests__/directives/vModel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ describe('vModel', () => {
it('should work with checkbox and true-value/false-value', async () => {
const component = defineComponent({
data() {
return { value: null }
return { value: 'yes' }
},
render() {
return [
Expand All @@ -301,23 +301,26 @@ describe('vModel', () => {
const input = root.querySelector('input')
const data = root._vnode.component.data

input.checked = true
triggerEvent('change', input)
await nextTick()
expect(data.value).toEqual('yes')
// DOM checked state should respect initial true-value/false-value
expect(input.checked).toEqual(true)

data.value = 'no'
input.checked = false
triggerEvent('change', input)
await nextTick()
expect(input.checked).toEqual(false)
expect(data.value).toEqual('no')

data.value = 'yes'
await nextTick()
expect(input.checked).toEqual(true)

input.checked = false
data.value = 'no'
await nextTick()
expect(input.checked).toEqual(false)

input.checked = true
triggerEvent('change', input)
await nextTick()
expect(data.value).toEqual('no')
expect(data.value).toEqual('yes')
})

it('should work with checkbox and true-value/false-value with object values', async () => {
Expand Down
5 changes: 3 additions & 2 deletions packages/runtime-dom/src/directives/vModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ export const vModelText: ModelDirective<
}

export const vModelCheckbox: ModelDirective<HTMLInputElement> = {
created(el, binding, vnode) {
setChecked(el, binding, vnode)
created(el, _, vnode) {
el._assign = getModelAssigner(vnode)
addEventListener(el, 'change', () => {
const modelValue = (el as any)._modelValue
Expand Down Expand Up @@ -130,6 +129,8 @@ export const vModelCheckbox: ModelDirective<HTMLInputElement> = {
}
})
},
// set initial checked on mount to wait for true-value/false-value
mounted: setChecked,
beforeUpdate(el, binding, vnode) {
el._assign = getModelAssigner(vnode)
setChecked(el, binding, vnode)
Expand Down

0 comments on commit 48f00c0

Please sign in to comment.