Issue
I am attempting to build a basic todo list app using Vue 3 Composition API with typescript. I previously configured the setup function for my component to use a ref method to handle reactivity of user input passed into the listItems array. Now I am attempting to refactor my setup function to use a reactive method, with the properties of my todo app arranged as an object. In the state object that I created, I initialized newTodo as an empty string, and listItems as a string array. The addTodo function is then called to push user-inputted newTodo values into the listItems array. However, with this setup I am now getting a parsing error that says an identifier is expected. This error appears to target the listItems property in the state object: listItems: <string[]>[]. I want to assume this means an id needs to be added to the state object in order to be appended to each list item, but am unsure how to handle this dynamically. Any idea how to resolve this? See 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>
Solution
You have to use the generic in reactive like this:
const state = reactive<{ newTodo: string; listItems: string[] }>({
newTodo: "",
listItems: [],
});
you can also cast the listItems state like this :
const state = reactive({
newTodo: "",
listItems: [] as string[],
});
But I think the first solution is better
Answered By - Adri HM
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.