vue实现增减框
Vue 实现增减框的方法
使用 v-for 和数组控制数量
在 Vue 中可以通过 v-for 指令动态渲染增减框,结合数组的 push 和 splice 方法实现增减功能。
<template>
<div>
<button @click="addItem">增加</button>
<div v-for="(item, index) in items" :key="index">
<input v-model="item.value">
<button @click="removeItem(index)">删除</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: []
}
},
methods: {
addItem() {
this.items.push({ value: '' })
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
使用计数器控制数量
对于简单的增减需求,可以使用计数器配合条件渲染来实现。
<template>
<div>
<button @click="count++">增加</button>
<button @click="count > 0 ? count-- : count">减少</button>
<div v-for="n in count" :key="n">
<input :placeholder="'输入框 ' + n">
</div>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
带验证的增减框
可以添加验证逻辑,确保增减操作符合业务规则。
<template>
<div>
<button @click="addBox" :disabled="boxes.length >= max">增加</button>
<div v-for="(box, index) in boxes" :key="index">
<input v-model="box.content">
<button @click="removeBox(index)">删除</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
boxes: [],
max: 5
}
},
methods: {
addBox() {
if (this.boxes.length < this.max) {
this.boxes.push({ content: '' })
}
},
removeBox(index) {
this.boxes.splice(index, 1)
}
}
}
</script>
使用组件封装
对于复杂场景,可以将增减框封装为独立组件。
<!-- AddRemoveBox.vue -->
<template>
<div class="add-remove-box">
<button @click="add">增加</button>
<div v-for="(item, index) in items" :key="index">
<slot :item="item" :index="index"></slot>
<button @click="remove(index)">删除</button>
</div>
</div>
</template>
<script>
export default {
props: {
initialItems: {
type: Array,
default: () => []
}
},
data() {
return {
items: [...this.initialItems]
}
},
methods: {
add() {
this.items.push({})
this.$emit('change', this.items)
},
remove(index) {
this.items.splice(index, 1)
this.$emit('change', this.items)
}
}
}
</script>
使用时通过插槽自定义内容:
<template>
<add-remove-box @change="handleChange">
<template #default="{ item, index }">
<input v-model="item.name" :placeholder="'名称' + index">
<input v-model="item.price" type="number" placeholder="价格">
</template>
</add-remove-box>
</template>
<script>
import AddRemoveBox from './AddRemoveBox.vue'
export default {
components: { AddRemoveBox },
methods: {
handleChange(items) {
console.log('当前项:', items)
}
}
}
</script>
这些方法涵盖了从简单到复杂的 Vue 增减框实现,可根据实际需求选择适合的方案。







