search

Home  >  Q&A  >  body text

Vuejs: Cannot modify reference within function, but can modify reference from template

I'm trying to learn Vue and ran into the following 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 fine, when I click the button, the text inside the div changes to changed name. But the following doesn't work, isn't the variable name available in the function? Also used defineExpose({name}) , still doesn't 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>

P粉533898694P粉533898694321 days ago379

reply all(1)I'll reply

  • P粉741678385

    P粉7416783852024-03-22 14:10:06

    You can use reference names within templates. But in scripts you should use name.value.

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

    reply
    0
  • Cancelreply