1、正常传值,举一个小例子,根据列表中科目类型的比例进行计算,对对应的input值进行计算:
<div class="column">
<el-form-item :label="'贷方比例'">
<el-input
v-model="creditRatio"
disabled/>
</el-form-item>
</div>
<div class="column">
<el-form-item :label="'借方比例'">
<el-input
v-model="borrowerRatio"
disabled/>
</el-form-item>
</div>
JS:
computed: {
creditRatio() {
let data = 0
for (let i = 0; i < this.tables.length; i++) {
if (this.tables[i].subjectType === 1) {
data = parseInt(data) + parseInt(this.tables[i].ratio)
}
}
return data
},
borrowerRatio() {
let data = 0
for (let i = 0; i < this.tables.length; i++) {
if (this.tables[i].subjectType === 0) {
data = parseInt(data) + parseInt(this.tables[i].ratio)
}
}
return data
}
},
计算属性中的KEY不能在data()中定义,这个需要注意
2、利用卡槽进行传值
<el-table :data="tableData">
<el-table-column label="备注" width="210" align="center">
<template slot-scope="scope">
<span>{{changeRemarkLength(scope.row.remark)}}</span>
</template>
</el-table-column>
</el-table>
<script>
data () {
return {
tableData:[]
}
},
methods: {
},
//计算属性
computed:{
//改变备注的长度,长度大于14位就用...代替剩余内容
changeRemarkLength(){
//text就是所传参数
return function (text) {
if(text.length > 14){
return text.slice(0,14)+"...";
}else{
return text;
}
}
}
}
</script>
说明:
1、计算属性传参,方法里写成 return function (val) {}形式
2、<template slot-scope="scope"> slot-scope="scope"代表插槽的意思,这里 scope 代表行 data。scope.row取整行数据
3、computed运行机制:
computed:{
totalPrice(){
let totalPrice = 0
this.listOfArticles.forEach(food => {
totalPrice += food.price + food.count
})
return totalPrice // 我们只需要在模板中使用 {{ totalPrice }} 就可以表示选中的商品价格
}
}
computed是基于它的依赖进行缓存的。computed只有在它的相关依赖发生变化才会重新计算求值。在本例子中只要价格和数量发生变化, totalPrice方法才会执行, 而只要价格和数量没有发生变化,多次访问会立即返回之前的计算结果,而不必再次执行计算。