1. 计算属性就是根据一定的逻辑,将一个新属性与data数据的某个属性进行关联,由此获取与原数据对应的值
在一个计算属性里可以完成各种复杂的逻辑,包括运算、函数调用等,只要最终返回一个结果就可以
2.简单的说,就是data中有数据A,另一个B结果与A有一定的关联,需要A通过计算得到,既可以用计算属性;
如:
<div id="test">
你输入的:<input type="text" v-model="message"><br/>
将变成:<input type="text" v-model="newMessage" disabled>
</div>
let vm = new Vue({
el:'#test',
data:{ message:''},
computed:{
newMessage:function(){
return this.message==''?'':this.message+',我是新数据!';
},
newMessageForTest:{
get:function(){
return this.message==''?'':this.message+',我是新数据!';
}
}
}
});
message发生变化 newMessage返回的值也发生变化,message没有发生变化,newMessage的值不会发生变化;
计算属性的作用就是让 Vue 知道 vm.newMessage 依赖于 vm.message,当 vm.message发生改变时,所有依赖 vm.newMessage 的绑定也会更新。
在电商项目中,计算属性的一个典型使用场景就是购物车页面 通过勾选购物车中的商品或修改商品购买数量计算总价
<template> <div class="CalAttribute"> <p>购物车效果用'计算属性'获得变化的总金额、总数量</p> <el-table :data="tableData" max-height="250"> <el-table-column prop="name" label="姓名" width="120"> </el-table-column> <el-table-column label="市区" width="160"> <template slot-scope="scope"> <el-row> <el-col :span="8"><el-button @click.native.prevent="ReduceNum(scope.$index, scope.row)">-</el-button></el-col> <el-col :span="8"><el-input v-model="scope.row.unitPrice"></el-input></el-col> <el-col :span="8"><el-button @click.native.prevent="IncreaseNum(scope.$index, scope.row)">+</el-button></el-col> </el-row> </template> </el-table-column> <el-table-column prop="price" label="产品单价" width="300"> </el-table-column> <el-table-column prop="amount" label="产品总价" width="120"> </el-table-column> <el-table-column fixed="right" label="操作" width="120"> <template slot-scope="scope"> <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text" size="small"> 移除 </el-button> </template> </el-table-column> </el-table> <el-row> <el-col :span="8">总购买价:{{amountPrice}}</el-col> <el-col :span="8">总购买数量:{{amountNum}}</el-col> <el-col :span="8"><el-button>清空购物车</el-button></el-col> </el-row> </div> </template> <script> export default { name: 'CalAttribute', data () { return { // amountPrice: 0, // amountNum: 0, tableData: [{ name: '王小虎1', city: '普陀区', price: '20.5', unitPrice: 1, amount: 20.5 }, { name: '王小虎2', city: '普陀区', price: '22', unitPrice: 1, amount: 22 }, { name: '王小虎3', city: '普陀区', price: '58.6', unitPrice: 1, amount: 58.6 }] } }, computed: { amountPrice () { let amountList = 0 this.tableData.forEach(function (item, index) { amountList += item.amount }) return amountList }, amountNum () { let unitPrice = 0 this.tableData.forEach(function (item, index) { unitPrice += item.unitPrice }) return unitPrice } }, methods: { // 删除对应项 deleteRow (index, rows) { rows.splice(index, 1) }, // 购物车减数量 ReduceNum (index, rows) { if (rows.unitPrice >= 1) { rows.unitPrice-- rows.amount = rows.price * rows.unitPrice } }, // 购物车增加数量 IncreaseNum (index, rows) { rows.unitPrice++ rows.amount = rows.price * rows.unitPrice } } } </script>