Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3 composition API data is not reactive

I have a simple app where I have a component for adding tasks and the main page where I want to show all added tasks. The problem is that when I add a new task it doesn't show in template where I render all tasks. I would like to re-use my AddTasks component and useTasks composition function to add tasks. But they're not showing up on the main page. What am I doing wrong?

Here is the repo to clone and try:

$ git clone https://github.com/martinszeltins/vue3-reactivity.git
$ cd vue3-reactivity
$ npm install
$ npm run serve

Here is my App.vue

<template>
    <div v-for="task in tasks">
        {{ task }}
    </div>

    <add-task />
</template>

<script>
    import AddTask from './components/AddTask.vue'
    import useTasks from './composition/useTasks.js'

    export default {
        components: {
            AddTask
        },

        setup() {
            const { tasks } = useTasks()

            return { tasks }
        },
    }
</script>

And here is the AddTask component

<template>
    <button @click="addTask">
        Add new task
    </button>
</template>

<script>
    import useTasks from '../composition/useTasks.js'

    export default {
        setup()
        {
            const { add } = useTasks()

            function addTask() {
                add('My new task')
            }

            return { addTask }
        }
    }
</script>

And the useTasks composition function

import { ref } from 'vue'

export default function useTasks() {
    const tasks = ref(['First task'])

    function add(task) {
        alert(`Adding task - ${task}`)
        tasks.value.push(task)
    }

    return { tasks, add }
}
like image 240
Liga Avatar asked May 16 '26 15:05

Liga


1 Answers

It's because your array is reset every time the function runs.

Move it outside the function and it should work:

import { ref } from 'vue';

const tasks = ref(['First task']);

export default function useTasks() {
    function add(task) {
        alert(`Adding task - ${task}`);
        tasks.value.push(task);
    }

    return { tasks, add };
}
like image 62
Daniel_Knights Avatar answered May 19 '26 05:05

Daniel_Knights