vue实现多选项求和
实现多选项求和的基本思路
在Vue中实现多选项求和功能,通常需要绑定一组复选框或单选按钮到数据模型,并通过计算属性实时计算选中项的和。核心在于利用v-model管理选中状态,结合computed属性动态计算总和。
数据准备与绑定
定义选项数组和选中状态数据。每个选项对象应包含value(数值)和selected(布尔值)属性:
data() {
return {
options: [
{ value: 10, selected: false },
{ value: 20, selected: false },
{ value: 30, selected: false }
]
}
}
模板中的复选框绑定
使用v-for渲染选项列表,并通过v-model双向绑定到selected属性:

<div v-for="(option, index) in options" :key="index">
<input
type="checkbox"
v-model="option.selected"
:value="option.value"
>
<label>{{ option.value }}</label>
</div>
计算总和
通过计算属性过滤出选中的选项,并累加它们的值:
computed: {
totalSum() {
return this.options
.filter(opt => opt.selected)
.reduce((sum, opt) => sum + opt.value, 0)
}
}
显示结果
在模板中直接显示计算属性结果:

<p>总和: {{ totalSum }}</p>
完整示例代码
<template>
<div>
<div v-for="(option, index) in options" :key="index">
<input
type="checkbox"
v-model="option.selected"
:value="option.value"
>
<label>{{ option.value }}</label>
</div>
<p>总和: {{ totalSum }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 10, selected: false },
{ value: 20, selected: false },
{ value: 30, selected: false }
]
}
},
computed: {
totalSum() {
return this.options
.filter(opt => opt.selected)
.reduce((sum, opt) => sum + opt.value, 0)
}
}
}
</script>
动态添加选项的实现
如果需要支持动态添加新选项,可以扩展方法:
methods: {
addOption(value) {
this.options.push({ value, selected: false })
}
}
使用单选按钮的变体
若改为单选模式,只需将checkbox改为radio,并确保v-model绑定到同一个变量:
<input
type="radio"
v-model="selectedValue"
:value="option.value"
>
对应的计算属性简化为:
computed: {
totalSum() {
return this.selectedValue || 0
}
}






