typescript - 如何使用响应式(Reactive)方法设置 Vue 3 Composition API(Typescript)待办事项列表应用程序

标签 typescript vue.js vue-component vuejs3 vue-composition-api

我正在尝试使用带有 typescript 的 Vue 3 Composition API 构建一个基本的待办事项列表应用程序。我之前为我的组件配置了设置函数以使用 ref处理传入 listItems 的用户输入的 react 性的方法大批。现在我正在尝试重构我的设置函数以使用 reactive方法,将我的待办事项应用程序的属性排列为一个对象。在我创建的状态对象中,我初始化了 newTodo作为空字符串,listItems作为字符串数组。 addTodo然后调用函数将用户输入的 newTodo 值推送到 listItems 数组中。但是,通过此设置,我现在收到一个解析错误,指出需要一个标识符。此错误似乎针对状态对象中的 listItems 属性:listItems: <string[]>[] .我想假设这意味着需要将一个 id 添加到状态对象以便附加到每个列表项,但我不确定如何动态处理它。知道如何解决这个问题吗?见下面的代码:

模板

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

最佳答案

你必须像这样在 reactive 中使用泛型:

const state = reactive<{ newTodo: string; listItems: string[] }>({
  newTodo: "",
  listItems: [],
});

您还可以像这样转换 listItems 状态:

const state = reactive({
  newTodo: "",
  listItems: [] as string[],
});

但我认为第一种方案更好

关于typescript - 如何使用响应式(Reactive)方法设置 Vue 3 Composition API(Typescript)待办事项列表应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70732457/

相关文章:

vue.js - 如何修复此错误 : "v-model cannot be used on a prop, because local prop bindings are not writable?"

javascript - 如何在 TypeScript 中进行方法重载?

javascript - Vue 中的无限更新循环

javascript - forEach 不是 JavaScript 数组的函数错误

vue.js - 我有一个 Electron 项目,我想与它一起使用vueJS

javascript - [Vue 警告] : Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders

javascript - 如何在 Typescript 中声明 NPM 的模块公共(public)类型定义

javascript - 在 VScode 编辑器中显示 Javascript 的 Intellisense 错误

css - 从 Angular Typescript 导入 css3/compass

javascript - Vue.js 缺少 Angular 2 的哪些模块?