What works:
I want to render an element only if some boolean value is true using Vue 3. This is an example following the Vue 3 documentation and it works just fine:
Template:
...
<div id="btnReady" @click="ready = !ready">
<img v-if="!ready" src="ready.svg" alt="" />
<img v-else src="unready.svg" alt="" />
</div>
...
Script:
<script setup>
import { ref } from "vue";
let ready = ref(false);
</script>
What I do not understand:
That makes perfect sense to me, except i don't really understand the need of ref()
. I read the documentation about it and didn't really understand how/why vue requires the initialization like this let ready = ref(false)
and why using let ready = false
won't react to changes to the ready
variable.
What does NOT work:
Beside toggling a boolean value, the onclick
handler should also perform some other actions. So instead of toggling the value like this onclick="ready = !ready"
i want to call a function onclick="toggleReady"
. The value of ready
will be toggled within the function and some other actions will be executed.
The function is executed on click just fine but Vue does NOT react to the changes of the ready
variable and the v-if
statement does not "work" properly -> the element is still visible.
Template:
<div id="btnReady" @click="toggleReady">
<img v-if="!isReady" src="ready.svg" alt="" />
<img v-else src="unready.svg" alt="" />
</div>
Script:
<script setup>
import { ref } from "vue";
let ready = ref(false);
let toggleReady = () => {
ready = !ready;
// do some more stuff
};
</script>
Can someone explain me this behaviour and how I can fix it?
PS: I also tried using a computed
property in the v-if
statement instead of a normal variable. Didn't work...