vue3组合式api+typescript删除功能
时间: 2023-11-24 14:07:08 浏览: 39
对于Vue 3组合式API和TypeScript,你可以使用以下步骤来实现删除功能:
1. 首先,在你的组件中引入`ref`和`reactive`:
```typescript
import { ref, reactive } from 'vue';
```
2. 创建一个响应式的数据对象,用于存储你的列表数据:
```typescript
interface Item {
id: number;
name: string;
}
const items = reactive<Item[]>([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
```
3. 创建一个删除功能的方法:
```typescript
const deleteItem = (id: number) => {
const index = items.findIndex(item => item.id === id);
if (index !== -1) {
items.splice(index, 1);
}
};
```
4. 在模板中循环渲染列表,并为每个项添加删除按钮:
```html
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
<button @click="deleteItem(item.id)">删除</button>
</li>
</ul>
</template>
```
5. 将删除方法和数据绑定到组件中的实例:
```typescript
export default {
setup() {
return {
items,
deleteItem,
};
},
};
```
现在,当你点击删除按钮时,相应的项将从列表中删除。请注意,这只是一个简单的示例,你可以根据自己的需求进行调整和扩展。