JS_*_*e18 3 typescript vue.js vue-component vuejs3 vue-composition-api
我正在尝试使用 Vue 3 Composition API 和 typescript 构建一个基本的待办事项列表应用程序。我之前为我的组件配置了设置函数,以使用一种ref方法来处理传递到listItems数组中的用户输入的反应性。现在,我尝试重构我的设置函数以使用一种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>
Run Code Online (Sandbox Code Playgroud)
脚本
<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>
Run Code Online (Sandbox Code Playgroud)
您必须像这样使用泛型reactive:
const state = reactive<{ newTodo: string; listItems: string[] }>({
newTodo: "",
listItems: [],
});
Run Code Online (Sandbox Code Playgroud)
您还可以listItems像这样转换状态:
const state = reactive({
newTodo: "",
listItems: [] as string[],
});
Run Code Online (Sandbox Code Playgroud)
但我认为第一个解决方案更好
| 归档时间: |
|
| 查看次数: |
6903 次 |
| 最近记录: |