I am attempting to build a basic todo list app using Vue 3 Composition API with Typescript. I configured the submit function in the form to call addTodo()
in the setup function. My intention is to push user-inputted values to the listItems
array, which is initialized with the ref
method. In my addTodo()
function I added listItems.value.push(newTodo.value)
in order to pass the inputted value to the array. However, I am getting an error on the newTodo.value parameter, saying Argument of type 'string' is not assignable to parameter of type 'never'
. I am new to Composition API in Vue 3. How can I go about resolving this type error?
See my code below:
Template
<template>
<div class="container">
<form @submit.prevent="addTodo()">
<label>New ToDo</label>
<input
v-model="newTodo"
name="newTodo"
autocomplete="off"
>
<button>Add ToDo</button>
</form>
<div class="content">
<ul>
<li v-for="listItem in listItems" :key="listItem">
<h3>{{ listItem }}</h3>
</li>
</ul>
</div>
</div>
</template>
Script
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'Form',
setup() {
const newTodo = ref('');
const listItems = ref([]);
const addTodo = () => {
listItems.value.push(newTodo.value)
newTodo.value = ''
}
return { newTodo, listItems, addTodo }
}
});
</script>
You need to declare typing for listItems
like this:
const listItems = ref<string[]>([]);
otherwise TypeScript won't know what type of array listItems
is
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.