实现的是用vue项目实现原生的table求一列的数值总和,其中数值是后期通过input输入的
效果看这里
这里要说的是 每个人的英语分数总和,因为英语是后期输入的, 不是数据库返回的,所以这边有点麻烦.
这里写的两种方法实现, 一种是方法methods, 一种就是计算属性computed
html代码
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- <script src="//unpkg.com/element-ui@2.4.11/lib/index.js"></script> -->
<div id="app">
<template>
<table border>
<thead>
<tr>
<td>ID</td>
<td>名称</td>
<td>数学</td>
<td>物理</td>
<td>英语手动打分</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData6" :key="index">
<th>{{item.id}}</th>
<th>{{item.name}}</th>
<th>{{item.amount1}}</th>
<th>{{item.amount2}}</th>
<th>
<div>
<input type="text" placeholder='打分啊' v-model="item.amount4">
<!-- <input type="text" placeholder='打分啊' v-model="item.amount4" @change="blurInput(index)"> -->
</div>
</th>
</tr>
<tr>
<th>总计</th>
<th>N/A</th>
<th>{{sumAmount}}</th>
<th>{{sumMoney}}</th>
<th>
{{sunCount}}
</th>
</tr>
</tbody>
</table>
</template>
</div>
没放样式代码了, 这里只实现功能
js代码
<script>
var Main = {
data() {
return {
tableData6: [{
id: '12987122',
name: '王小虎111',
amount1: '234',
amount2: '3.2',
amount3: 10,
amount4: ''
}, {
id: '12987123',
name: '王小虎222',
amount1: '165',
amount2: '4.43',
amount3: 12,
amount4: ''
}, {
id: '12987124',
name: '王小虎333',
amount1: '324',
amount2: '1.9',
amount3: 9,
amount4: ''
}, {
id: '12987125',
name: '王小虎444',
amount1: '621',
amount2: '2.2',
amount3: 17,
amount4: ''
}, {
id: '12987126',
name: '王小虎555',
amount1: '539',
amount2: '4.1',
amount3: 15,
amount4: ''
}],
};
},
computed: {
sumAmount() {
return this.tableData6.map(row => row.amount1).reduce((acc, cur) => (parseInt(cur) + acc), 0)
},
sumMoney() {
return this.tableData6.map(row => row.amount2).reduce((acc, cur) => (parseFloat(cur) + acc), 0)
},
// 方法一:计算属性
sunCount() {
console.log('this.tableData6.map(row => row.amount4)', this.tableData6.map(row => row.amount4))
var bb = [];
for(var i in this.tableData6.map(row => row.amount4)){
if(this.tableData6.map(row => row.amount4)[i]) {
bb.push(this.tableData6.map(row => row.amount4)[i])
}
}
return bb.reduce((acc, cur) => (parseFloat(cur) + acc), 0)
// return this.tableData6.map(row => row.amount4).reduce((acc, cur) => (parseFloat(cur) + acc), 0)
// let num = 0
// for( let i = 0 ; i < this.tableData6.length ; i++) {
// num += Number(this.tableData6[i].amount4)
// }
// return num
}
},
methods: {
// 方法二: 通过change事件实现
// blurInput(index) {
// console.log('index', this.tableData6)
// let num = 0;
// this.tableData6[index].amount4 = number
// for( let i = 0 ; i < this.tableData6.length ; i++) {
// num += Number(this.tableData6[i].amount4)
// }
// this.englishAllNum = num
// },
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
</script>