const variables cannot be updated.
Vue version
"vue": "^3.2.37"
Link to minimal reproduction
B: https://stackblitz.com/edit/vitejs-vite-pxibx7?file=src%2FApp.vue&terminal=dev
Steps to reproduce
click button 1 click button 2 click button 3 click button 4
What is expected?
1 1 1 1
What is actually happening?
A 1 0 0 1 B 1 0 1 1
System Info
No response
Any additional comments?
Why do Playrground and Stackblitz produce different results, is this another bug?
No response
Yes, const variables cannot be changed in Javascript. No, this is not a bug. Is part of the language
Yes, const variables cannot be changed in Javascript. No, this is not a bug. Is part of the language
please reopen it.
first, at Stackblitz B, button 3 also is const , but is changed. and, Stackblitz B and plyground A has produce different results, it is not a bug? finally, const will complie to $setup.const, is not part of the language
first, at Stackblitz B, button 3 also is const , but is changed.
I don't see that behavior in the demos you linked.
If you click button 3, var_const_random
does not change despite the post-increment operator on it in the click
-handler. Its value is always 0
.
and, Stackblitz B and plyground A has produce different results, it is not a bug?
The only difference between the two is seen in the random number from {{ var_const_random + Math.random() }}
. That's expected behavior, as Math.random()
isn't going to produce exactly the same results on every machine.
button 3, left is 0 right is 1
What is expected? 1 1 1 1
What is actually happening? left 1 0 0 1 right 1 0 1 1
Ah, I see it now. It wasn't reproducing earlier because I wasn't properly following the reproduction steps. However, the behavior is the same in both StackBlitz and the Vue Playground.
There's not really a bug to fix here, but I believe this is what's happening:
In dev mode, the Vue compiler transforms
const var_const = 0
into a context object ($setup
), where the object receives a property of the same name ($setup.var_const
), initialized to the value ofvar_const
. That new property does not becomeconst
itself. This can be seen in theJS
tab in the Vue SFC playground, after toggling theDEV
mode button in the top bar.In production mode, the compiler does not wrap
var_const
in a context object. Instead,var_const
is used directly, so the modification would result in a runtime error, and the problem would not be reproducible.Upon clicking button 3, the
click
-handler increments$setup.var_const
, but the change is not automatically rendered because$setup.var_const
is not aref
.Upon clicking button 4, the
click
-handler updatesflush
(aref
), which causes the template to re-render, which renders the current value of$setup.var_const
.