簡體   English   中英

如何設置 Vue 3 Composition API (Typescript) 將用戶輸入的值推送到數組

[英]How to set up Vue 3 Composition API (Typescript) to push user-inputted value to array

我正在嘗試使用 Vue 3 Composition API 和 Typescript 構建一個基本的待辦事項列表應用程序。 我在表單中配置了提交 function 以在設置 function 中調用addTodo() 我的意圖是將用戶輸入的值推送到listItems數組,該數組使用ref方法初始化。 在我的addTodo() function 中,我添加了listItems.value.push(newTodo.value)以便將輸入的值傳遞給數組。 但是,我在 newTodo.value 參數上遇到錯誤,說Argument of type 'string' is not assignable to parameter of type 'never' 我是 Vue 3 中的 Composition API 的新手。如何解決此類錯誤?

請參閱下面的代碼:

模板

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

您需要像這樣聲明listItems的類型:

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

否則 TypeScript 將不知道listItems是什么類型的數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM