Home > Net >  Vuejs: Can't change ref inside function but can do from template
Vuejs: Can't change ref inside function but can do from template

Time:08-29

Am trying to learn Vue and have come across the below issue/problem.

<template>
    <div>{{ name }}</div>
    <button @click="name = 'changed name'">Change</button>
</template>
<script setup>
    import { ref } from 'vue';
    let name = ref('first');
</script>

The above works, when I click on the button, the text inside the div is changed to changed name. But the below does not work, is the variable name not available in the function? Have used defineExpose({name}) also, still does not work.

<template>
    <div>{{ name }}</div>
    <button @click="changeName">Change</button>
</template>
<script setup>
    import { ref } from 'vue';
    let name = ref('first');
    const changeName = () => {
        name = 'changed name';
    }
</script>

CodePudding user response:

Inside the template you can use the ref name. But inside the script you should use name.value.

    <script setup>
        import { ref } from 'vue';
        const name = ref('first');
        const changeName = () => {
            name.value = 'changed name';
        }
    </ script>
  • Related