Subscribe on changes!

Weird behaviour of computed setter/getter while using it with ref

avatar
Aug 9th 2023

Vue version

3.3.4

Link to minimal reproduction

https://play.vuejs.org/#eNp9UstOwzAQ/JXFF4pUWiFuIVQCxAEOgADBxRc32RSDY1t+hKIo/87GbVKQChfL3sfszKxbdmHtrInIMpb7wkkbwGOIFpTQq3POgudswbWsrXEBwpdFaOHVySCWCq9MbWPA8hEr6KBypoZDwjo8GxtacFhNodgW/qrimuvCaE+w6MOLcHDeV08qoTweEcaQlv45Oo3lvc72jc6XxigUekH9w6BJyzXACsPkKINtHlIMaEYgODjYTp01QkWkcQDdtD9J/0Tj50sfHpsJpjGyHDB+9dLcoX6E6TYC8vnGVLKQHgFrq0RAegHkbyeLtv0hDroun1MwJaUmHclvWkLxhsXH0qw5g+a4NiUqCu4a04by+YjOprQ2sq6Sq9m7N5p2m2gTENkjFbp7GyRZy1k2COJMKGU+b1MsuIjJitTTD98Tf/fEJ6PLg0OPrkHOxlwQjrzfpK+f7nBN9zFJAqKi6n+Sj+iNij3HTdll1CXR/lGX2N6kTyb16tlfrwNqP4jqie4Wyhl9t/7D/CV9R/d0dpr6aIGs+wbRYg7o

Steps to reproduce

  1. Create computed getter / setter
  2. Bind it to ref boolean variable
  3. In get method, return the neglected boolean ref variable
  4. Make a checkbox element with v-model bound to the computed setter/getter
  5. 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.

avatar
Aug 10th 2023

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.

https://github.com/vuejs/core/blob/3be4e3cbe34b394096210897c1be8deeb6d748d8/packages/reactivity/src/ref.ts#L155C1-L160C4

if the value not be changed. Reactive functions related to it will not trigger. so the computed getter not invoke