写在前面
一般实现多个文本输入计算求和的方法是通过el-input 的change事件或者keyup.native 事件实现,
但是一般通过这两种方法实现计算求和,一般都需要点击页面某一处后,才会调用方法实现求和,实现不了实时自动求和
此时考虑使用 computed和watch;关于computed和watch 参考
https://cn.vuejs.org/v2/api/#computed
https://cn.vuejs.org/v2/api/#watch
代码实现示例
使用computed和watch实现多数据求和示例
<template>
<div>
<el-form :inline="true" :rules="rules" ref="ruleForm1" :model="formInline" id="form_table" label-width="170px">
<el-row type="flex" class="row-bg edit_form">
<el-col :span="12">
<el-form-item label="总支出:" >
<el-input v-model="formInline.totalMoney" disabled>
</el-input>
</el-form-item>
</el-col>
/el-row>
</el-form>
</div>
<div style="float:right"><el-button type="primary" size="small" @click="addData()">添加</el-button></div>
<div>
<el-form :model="formInline" ref="outputForm">
<el-table :data="formInline.monthData" border :header-cell-style="headerStyle" :cell-style="headerCellStyle">
<el-table-column type="index" label="序号" width="80"></el-table-column>
<el-table-column label="月份">
<template slot-scope="scope">
<el-form-item :prop="'dayPlanOutputs.'+scope.$index+'.month'" :rules="rules.month">
<el-date-picker v-model="scope.row.month" type="month" format="yyyy-MM" value-format="yyyy-MM" placeholder="选择月份"
style="width:95%">
</el-date-picker>
</el-form-item>
</template>
</el-table-column>
<el-table-column label="支出(元)" width="150">
<template slot-scope="scope">
<el-form-item :prop="'dayPlanOutputs.'+scope.$index+'.money'" :rules="rules.decimal">
<el-input v-model="scope.row.money">
</el-input>
</el-form-item>
</template>
</el-table-column>
<el-table-column label="操作" width="80">
<template slot-scope="scope">
<el-button style="color: #6a9dca" icon="el-icon-delete" type="text" size="small" @click="delData(scope.$index)">
删除
</el-button>
</template>
</el-table-column>
</el-table>
</el-form>
</div>
</template>
<script>
import Cookies from "js-cookie";
import moment from "moment";
export default {
data() {
return {
reload: true,
tabIndex: "0",
contentStyleObj: {
height: "670px",
},
rules: {
month:[{
required: true,
message: "请选择月份",
trigger: "change",
}
],
decimal: [
{
message: "只能为最多两位小数数字",
trigger: "change",
pattern: /(^$)|^[0-9]+(.?[0-9]{1,2})?$/,
},
]
},
formInline: {
totalMoney:0,
monthData:[]
}
};
},
computed: {
monthDatas() {
return this.formInline.monthData;
}
},
watch: {
monthDatas: {
deep: true, // 深度监听
handler(newVal,oldVal) {
this.calculateSum();
}
}
},
mounted() {
},
methods: {
//添加数据行
addData(){
var newTunnelRow={
month:"",
money:0
};
this.$forceUpdate(this.formInline.monthData.push(newTunnelRow));
},
//删除数据航
delData(rowIndex){
this.$forceUpdate(this.formInline.monthData.splice(rowIndex, 1));
},
//计算求和
calculateSum(){
let total=0;
this.formInline.monthData.forEach((item)=>{
let money=(item.money)&&!isNaN(item.money)?Number(item.money):0;
total=total+money;
});
this.$set(this.formInline,"totalMoney",total);
}
}
};
</script>