Watching from the Start

A watcher runs only after a change, not when the app starts. Usually, that's what you want: there's no need to save a name that was just read. But some side effects are needed from the start, too. For those, there's another option, { immediate: true }. The watcher then runs once right when the app starts, and after every change, as before:

const name = ref("Ann");

watch(
    name,
    (newValue, oldValue) => {
        console.log(`${oldValue} → ${newValue}`);
    },
    { immediate: true },
);

The console shows undefined → Ann as soon as the app starts: on the first run, there's no old value yet. When the name changes to Bob, it shows Ann → Bob. You can also give both options at once: { deep: true, immediate: true }.

This exercise's app has a dark mode. The checkbox switches it, and the app already remembers the choice. localStorage keeps only text, so true is saved as "true", and === "true" turns it back into true or false when the app starts.

Dark mode colors the whole page, that is <body>, and <body> isn't in the component's template: the app lives inside <div id="app">. So :class can't reach it, and a watcher has to add and remove the class itself, with document.body.classList, as in the JavaScript course.

watchEffect. Vue has one more kind of watcher, watchEffect(). You give it only the function. It runs at once, and again whenever a ref that it reads changes, the way a computed value is worked out again:

watchEffect(() => {
    console.log(`Dark mode: ${dark.value}`);
});

It's shorter, but you can't see at a glance what it watches. This course uses watch().

Computed or watch? When you need a value to show, use a computed value: it returns the value, and Vue keeps it up to date. When something should happen because a value changed, such as saving it, use a watcher. A watcher that only sets another ref, as in watch(order, () => { total.value = … }), should be a computed value instead.

Instructions

  1. Make the checkbox switch dark mode: when dark changes to true, add the class dark to document.body, and when it changes to false, remove it. The page's style makes body.dark dark.

  2. Make a saved dark mode work from the start: check the box and click Run. The box stays checked, and the page has to stay dark, too.