Home > Back-end >  How to set up Vue 3 Composition API (Typescript) to push user-inputted value to array
How to set up Vue 3 Composition API (Typescript) to push user-inputted value to array

Time:01-16

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 >
      <form @submit.prevent="addTodo()">
          <label>New ToDo</label>
          <input
              v-model="newTodo"
              name="newTodo"
              autocomplete="off"
          >
          <button>Add ToDo</button>
      </form>

    <div >
      <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>

CodePudding user response:

You need to declare typing for listItems like this:

const listItems = ref<string[]>([]);

otherwise TypeScript won't know what type of array listItems is

  •  Tags:  
  • Related