Setting vars in composition API?

16 Views Asked by At

I'm using vue 3 composition api and I am struggling understanding setting vars, if I should use myVar.value or not?

For example, how should the following be set?

<script setup>

const active = ref(false);

function show(){
    active = true;
    active.value = true;
    this.active = true;
}

Which way?

1

There are 1 best solutions below

0
Erich Buelow On

In the script tag, state defined using ref() should be accessed using .value :

<script setup>
const active = ref(false)

function show() {
    active.value = true
}
</script>

In the template, state can be accessed directly :

<template>
    <h1 v-if="active">Hello, World!</h1>
</template>

If using defining state using reactive(), .value is not used :

<script setup>
    const greetings = reactive({ 'classic': 'Hello, World! })
    console.log(greetings.classic)
</script>
<template>
    <h1>{{ greetings.classic }}</h1>
</template>

Documentation: Vue 3 Reactivity API: Core