ref state not work for first time !! onBeforeMount run afetr mount !!
Vue version
3.3.4
Link to minimal reproduction
https://codesandbox.io/p/sandbox/wandering-violet-7tm4wr
Steps to reproduce
What is expected?
I expect that when the state changes, and it is passed to the prop component, that prop is also reactive and reacts to the change.
What is actually happening?
When the theme is in dark mode, when I first open the page in the browser (or refresh), I expect the icon inside the Navigation to be the sun icon. But this is not happening!!
I should add that this icon changes the theme when clicked. I click, but the icon does not change for the second time. From the third time onwards, it has the performance that I expect.
System Info
System:
OS: Linux 6.4 Arch Linux
CPU: (4) x64 Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
Memory: 1.26 GB / 7.64 GB
Container: Yes
Shell: 5.9 - /usr/bin/zsh
Binaries:
Node: 20.5.1 - /usr/bin/node
Yarn: 1.22.19 - /usr/bin/yarn
npm: 9.8.1 - /usr/bin/npm
Browsers:
Firefox Browser: 117.0
Any additional comments?
No response
onBeforeMount(() => {
theme.value = window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
if (!localStorage.getItem("theme")) {
+ localStorage.setItem("theme", is_dark_mode.value ? "dark" : "light");
- localStorage.setItem("theme", is_dark_mode? "dark" : "light");
}
// @ts-ignore
theme.value = localStorage.getItem("theme");
theme.value == "dark" && document.documentElement.classList.add("dark");
+ changeTheme()
});
onBeforeMount(() => { theme.value = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; if (!localStorage.getItem("theme")) { + localStorage.setItem("theme", is_dark_mode.value ? "dark" : "light"); - localStorage.setItem("theme", is_dark_mode? "dark" : "light"); } // @ts-ignore theme.value = localStorage.getItem("theme"); theme.value == "dark" && document.documentElement.classList.add("dark"); + changeTheme() });
At least you were testing the code you wrote ...
The reason for this is that onBeforeMount is run after the elements enter the DOM !!
See now to find out ( ThemeSwitcher component ) : https://codesandbox.io/p/sandbox/wandering-violet-7tm4wr
@yyx990803