Weird behaviour of computed setter/getter while using it with ref
Vue version
3.3.4
Link to minimal reproduction
Steps to reproduce
- Create computed getter / setter
- Bind it to ref boolean variable
- In get method, return the neglected boolean ref variable
- Make a checkbox element with v-model bound to the computed setter/getter
- Click / unclick
What is expected?
The value should change from false to true on every click to checkbox element
What is actually happening?
It looks like the computed getter registers only every second click.
System Info
No response
Any additional comments?
I know that this is not real world scenario, the way I am using this computed getter is that I have a checkbox which you can uncheck but before it became unchecked, there is some more logic behind it.
What I did is a really minimal repro on playground. Thanks for understanding.
TLDR;when u first click checkbox. the testVar
not change . so the computed getter not be invoked !
——————————————————————
let`s figure out why does this happen.
at first. when the page render.
<input type="checkbox" v-model="isTurnedOn">
the checkbox get the isTurnedOn
value. so it invoke get(): boolean { return !testVar.value; },
. the testVar
is false. so the isTurnedOn
value is true. so the checkbox is selected. although the isTurnedOn
is true. but the testVar
is false.
and then. when u first click checkbox . the set
is invoked . set(newValue: boolean): void { testVar.value = newValue; },
. the newValue
. ( the param !) is false. at this time. the testVar
also is false . so the testVar
not change.
if the value not be changed. Reactive functions related to it will not trigger. so the computed getter not invoke
As a TLDR for what @yangliguo7 correctly explained: you would need to also invert the newValue in the setter: