I am in the process of transitioning from Vue's Options API to the Composition API, and as part of this transition, I have built a small Todo App.
Within App.vue
, my code looks like this:
<template>
<div id="app">
<div class="card">
<Header />
<List />
<AddTodo @add-todo="addTodo" />
</div>
</div>
</template>
<script>
import { ref, onMounted, watch } from 'vue';
import Header from './components/Header.vue';
import List from './components/List.vue';
import AddTodo from './components/Add.vue';
export default {
name: 'App',
components: {
Header,
List,
AddTodo,
},
methods: {
addTodo: function (text) {
let newTodo = {
done: false,
text: text,
};
if (text.length > 2) {
console.log(newTodo);
// this.todos.push(newTodo);
}
},
},
};
</script>
In components/List.vue
, you'll find:
<template>
<ul>
<Item
v-for="(todo, index) in todos"
@toggle-todo="toggleTodo(item, index)"
@delete-todo="deleteTodo(item, index)"
:item="todo"
:key="index"
/>
</ul>
</template>
<script>
import { ref, onMounted, watch } from 'vue';
import Item from './Item.vue';
export default {
name: 'List',
components: {
Item,
},
setup() {
const todos = ref([
{
text: 'Animi, odit facere.',
done: true,
},
{
text: 'Lorem ipsum dolor sit.',
done: false,
},
{
text: 'Dolor sit amet consectetur.',
done: true,
},
]);
return { todos };
},
methods: {
toggleTodo: function (item, index) {
this.todos[index].done = !this.todos[index].done;
},
deleteTodo: function (item, index) {
if (confirm('Are you sure?')) {
this.todos.splice(index, 1);
}
},
},
};
</script>
As shown above, I have defined the todos
array within the list component, where it makes the most sense. The main purpose of App.vue is to act as a container for the other components.
Within components/Add.vue
, I have created the form used to add an item to the list of todos.
<template>
<form class="card-footer" @submit.prevent="$emit('add-todo', text)">
<input type="text" v-model="text" />
<button type="submit">Add</button>
</form>
</template>
<script>
import { ref, onMounted, watch } from 'vue';
export default {
name: 'AddTodo',
setup() {
const text = ref('');
return { text };
},
};
</script>
Since the todos
array is not contained in App.vue
, the line this.todos.push(newTodo)
, which I have commented out, will not work.
I am trying to figure out the best way to push the newTodo
object into the todos
array within the child component List.vue
. Any suggestions on how to achieve this seamlessly?