I am in the process of creating a simple todo list application using Vue 3 Composition API and TypeScript. Initially, I set up the function for my component to utilize the ref
method to manage the reactivity of user input inserted into the listItems
array. Now, I'm looking to refactor my setup function to use the reactive
method, organizing the properties of my todo app as an object. Within the state object I defined, I set newTodo
as an empty string and listItems
as an array of strings. The addTodo
function is supposed to add newTodo values entered by the user to the listItems array. However, after making these changes, I encountered a parsing error indicating the need for an identifier. This error seems to be targeting the listItems property within the state object: listItems: <string[]>[]
. I suspect that this means an id should be included in the state object in order to associate it with each list item dynamically. Do you have any suggestions on how to resolve this issue? Please see the code below:
Template
<template>
<div class="container">
<form @submit.prevent="addTodo()">
<label>New ToDo</label>
<input
v-model="state.newTodo"
name="newTodo"
autocomplete="off"
>
<button>Add ToDo</button>
</form>
<div class="content">
<ul>
<li v-for="listItem in state.listItems" :key="listItem">
<h3>{{ listItem }}</h3>
</li>
</ul>
</div>
</div>
</template>
Script
<script lang="ts">
import { defineComponent, reactive } from 'vue';
export default defineComponent({
name: 'Form',
setup() {
const state = reactive({
newTodo: '',
listItems: <string[]>[]
})
const addTodo = () => {
state.listItems.push(state.newTodo)
state.newTodo = ''
}
return { state, addTodo }
}
});
</script>