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 }
}
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 };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With