需求
点击+按钮实现添加多条数据,不超过10条
点击-按钮实现删除数据,至少保留一条
效果如下图
组件
<!--
* @Author: SunnyYang
* @Date: 2024-01-19 09:09:51
* @LastEditors: SunnyYang
* @LastEditTime: 2024-02-02 17:45:14
* @Description:
-->
<template>
<div class="icon-box">
<!-- v-if="currentIndex + 1 < maxLength" -->
<img class="icon-add" src="@/assets/images/icon_add_round_fill.png" alt="" srcset="" @click="handleClickAdd" />
<!-- v-if="currentIndex > 0" -->
<img
class="icon-remove"
src="@/assets/images/icon_remove_fill.png"
alt=""
srcset=""
@click="() => handleClickRemove(currentIndex)"
/>
</div>
</template>
<script setup name="AddRemoveIcon">
import { ElMessage } from 'element-plus'
//1-10条
const props = defineProps({
currentIndex: {
type: Number,
default: 0,
},
maxLength: {
type: Number,
default: 10,
},
minLength: {
type: Number,
default: 1,
},
listLength: {
type: Number,
default: 0,
},
onAdd: {
type: Function,
default: () => {},
},
onRemove: {
type: Function,
default: () => {},
},
})
function handleClickAdd() {
if (props.listLength < props.maxLength) {
props.onAdd()
} else {
ElMessage.warning('最多添加10条')
return
}
}
function handleClickRemove(index) {
if (props.listLength === props.minLength) {
ElMessage.warning('至少保留一条')
return
} else {
props.onRemove(index)
}
}
</script>
<style lang="scss" scoped>
.icon-box {
display: inline-flex;
align-items: center;
margin-left: 8px;
margin-bottom: 18px;
.icon-add,
.icon-remove {
width: 24px;
height: 24px;
cursor: pointer;
}
}
</style>
应用
<AddRemoveIcon
:on-add="() => handleOnAdd(propKey)"
:on-remove="() => handleOnRemove(index, propKey)"
:currentIndex="index"
:listLength="formData[propKey].length"
:maxLength="10"
/>
//添加多条数据
function handleOnAdd(propKey) {
formData.value[propKey].push('')
}
//=删除
function handleOnRemove(index, propKey) {
formData.value[propKey].splice(index, 1)
}
//修改
function handleOnChange(propKey, index, val) {
formData.value[propKey][index] = val
}
icon