Vuejs: Cannot modify reference within function, but can modify reference from template
P粉533898694
P粉533898694 2024-03-21 19:10:21
0
1
322

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粉533898694
P粉533898694

reply all(1)
P粉741678385

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template