computed又被称作计算属性,用于动态的根据某个值或某些值的变化,来产生对应的变化,computed具有缓存性,当无关值变化时,不会引起computed声明值的变化。产生一个新的变量并挂载到vue实例上去。
一、computed简写形式
<template>
<div>
<div>姓:<input type="text" v-model="surname"></div>
<div>名:<input type="text" v-model="name"></div>
<div>姓名:<input type="text" v-model="fullName"></div>
</div>
</template>
<script>
export default {
computed:{
fullName(){
return this.surname+'~'+this.name
}
},
data(){
return{
surname:'勇敢',
name:'小陈',
}
}
}
</script>
<style>
</style>
当我们动态的去更改surname或name时,都会引起fullName的改变。
二、computed的完整形式
为什么说是computed的完整形式呢,因为computed的简写形式只是单独的完成了读的功能,二没办法去更改surname和name的值,下面我们进行computed的完整形式。
<template>
<div>
<div>姓:<input type="text" v-model="surname"></div>
<div>名:<input type="text" v-model="name"></div>
<div>姓名:<input type="text" v-model="fullName"></div>
</div>
</template>
<script>
export default {
computed:{
fullName:{
get(){
return this.surname+'~'+this.name
},
set(value){
var arr=value.split('~')
this.surname=arr[0]
this.name=arr[1]
}
}
},
data(){
return{
surname:'勇敢',
name:'小陈',
}
}
}
</script>
<style>
</style>
###computed使用场景
1、购物车--计算商品总价,这种操作就适合放在computed里面
computed: {
cartGoods () {
return this.$store.state.cartGoods; //state里定义的cardGoods全局变量
},
//计算商品总价,这种操作就适合放在computed里面
amount () {
let cartGoods = this.$store.state.cartGoods;
let result = 0;
cartGoods.forEach(good =>{
result += good.price * good.count;
})
return result;
},
//合计
pay () {
let result = this.amount - this.redPacket; //总价减去红包金额
if (result >= 49) {
this.needPostage = false;
} else {
this.needPostage = true;
}
if (this.needPostage) {
result += this.postage;
}
return result;
},
},