vue3按钮点击新增一行div,并且可以删除一行
时间: 2023-05-17 11:05:10 浏览: 495
可以使用 Vue3 的响应式数据和 v-for 指令来实现这个功能。首先,在 data 中定义一个数组,用于存储新增的行的数据。然后,在模板中使用 v-for 指令遍历这个数组,生成每一行的内容。新增行的按钮可以绑定一个方法,在方法中向数组中添加一条数据,然后 Vue3 会自动更新模板。删除行的按钮可以绑定一个方法,在方法中从数组中删除对应的数据。
以下是示例代码:
```html
<template>
<div>
<div v-for="(item, index) in items" :key="index">
<input type="text" v-model="item.text">
<button @click="removeItem(index)">删除</button>
</div>
<button @click="addItem">新增</button>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({
items: []
})
function addItem() {
state.items.push({ text: '' })
}
function removeItem(index) {
state.items.splice(index, 1)
}
return {
items: state.items,
addItem,
removeItem
}
}
}
</script>
```
在这个示例中,我们使用了 Vue3 的新特性 setup 函数来定义组件。setup 函数返回一个对象,包含了组件的数据和方法。我们使用 reactive 函数来创建一个响应式的数据对象 state,其中包含了一个空数组 items。addItem 方法向 items 数组中添加一条数据,removeItem 方法从 items 数组中删除对应的数据。模板中使用 v-for 指令遍历 items 数组,生成每一行的内容。