Vue 2.0 实现全选与单选及总价计算的完整代码
作者:松果时间:2026-10-22 06:03:39浏览:443
本文提供基于 Vue 2.0 和 vue-cli 的全选、单选及总价计算实现方案。针对现有方案不足,整理了一份简洁实用的代码示例,涵盖模板结构与逻辑处理,旨在帮助开发者快速掌握相关功能实现。
Vue 2.0 全选与单选及总价计算实现
因工作需求,且鉴于网络上现有的 Vue 2.0 结合 vue-cli 实现全选与单选的功能方案存在不适用之处,本文整理了一份简洁且实用的代码示例。该方案仅包含 126 行代码,旨在解决实际问题。
<template>
<div>
<table>
<tr>
<td><input type="checkbox" v-model="checkAll">全选({{checkedCount}})</td>
<td>产品名称</td>
<td>价格</td>
<td>数量</td>
</tr>
<tr v-for="(item,$index) in lists">
<td><span v-show="checkedCount===lists.length || item.checked===true">我被选中</span><input type="checkbox" :value="item.id" v-model="checked" @click="currClick(item,$index)"></td>
<td>{{item.productName}}</td>
<td>{{item.price}}</td>
<td>{{item.count}}</td>
</tr>
<tr>
总价:{{totalMoney}}
</tr>
</table>
</div>
</template>
<script>
export default{
data() {
return {
checked:[],
totalPrice:[],
lists : [
{
productName:'产品1',
price:'24',
count:'3',
id:1
},
{
productName:'产品2',
price:'25',
count:'6',
id:2
},
{
productName:'产品3',
price:'54',
count:'7',
id:3
}
]
}
},
computed:{
totalMoney:function(item,index){
let sum = 0;
for(let i=0;i<this.totalPrice.length;i++){
sum += this.totalPrice[i];
};
return sum;
},
checkAll: {
get: function() {
return this.checkedCount == this.lists.length;
},
set: function(value){
var _this = this;
if (value) {
this.totalPrice = [];
this.checked = this.lists.map(function(item) {
item.checked = true;
let total = item.price*item.count;
_this.totalPrice.push(total);
return item.id
})
}else{
this.checked = [];
this.totalPrice=[];
this.lists.forEach(function(item,index){
item.checked = false;
});
}
}
},
checkedCount: {
get: function() {
return this.checked.length;
}
}
},
methods:{
currClick:function(item,index){
var _this = this;
if(typeof item.checked == 'undefined'){
this.$set(item,'checked',true);
let total = item.price*item.count;
this.totalPrice.push(total);
console.log(this.totalPrice);
}else{
item.checked = !item.checked;
if(item.checked){
this.totalPrice = [];
this.lists.forEach(function(item,index){
if(item.checked){
let total = item.price*item.count;
_this.totalPrice.push(total);
}
});
}else{
this.totalPrice = [];
this.lists.forEach(function(item,index){
if(item.checked){
let total = item.price*item.count;
_this.totalPrice.push(total);
}
});
}
}
}
}
}
</script>
<style>
tr td{
width:200px;
background: #eee;
padding:10px 0;
}
</style>
运行效果如下所示:



以上内容为本文的全部分享,希望能为读者的学习提供有益参考。同时也欢迎读者继续支持本站,获取更多技术资源。
作者最新文章
Vue前端日历插件VCalendar集成与使用指南
2026-10-31 18:16:55
uniapp scroll-view 组件实战:Vue3 改造与滚动逻辑详解
2026-10-31 14:49:47
ElementUI el-calendar 周月视图切换与自定义实现
2026-10-31 14:48:43
Vue Element UI 结合 sortable.js 实现嵌套表格行内拖拽排序
2026-10-31 13:57:34
el-input 限制输入只允许输入浮点型的解决思路
2026-10-31 12:30:12
