计算属性指通过一系列运算之后,最终的得到一个属性值。这个动态计算出来的属性值可以被模板结构或methods方法使用
特点:
- 定义的时候,要被定义为方法
- 在使用计算属性的时候,当普通的属性使用即可
优点:
- 实现了代码的复用
- 只要计算属性中依赖的数据源变化了,则计算属性会自动重新求值
<script src="./vue.js"></script>
<style>
.box{
width: 100px;
height: 100px;
border: 1px solid #ccc;
/* background-color: aqua; */
}
</style>
</head>
<body>
<!-- 正常方法 -->
<div class="app">
r: <input type="text" v-model.number="r"><br>
g: <input type="text" v-model.number="g"><br>
b: <input type="text" v-model.number="b">
<div class="box" :style="{backgroundColor:`rgb(${r},${g},${b})`}">
{{` rgb(${r},${g},${b})`}}
</div>
<button @click="show">按钮</button>
</div>
<script>
new Vue({
el:".app",
data:{
r:0,
g:0,
b:0
},
methods:{
show(){
console.log(` rgb(${this.r},${this.g},${this.b})`);
}
}
})
</script>
<script src="./vue.js"></script>
<div class="app">
<p>总价:{{total}}</p>
<button @click="btn">计算</button>
</div>
<script>
const vm=new Vue({
el:".app",
data:{
list:[
{id:1,price:5000,name:"苹果",num:1},
{id:2,price:6600,name:"huawei",num:1},
]
},
methods:{
btn(){
// 每点击一次数量加一,价格跟着变化
this.list[0].price=5000
this.list[0].num +=1
}
},
// computed 计算属性,用来计算未来想要数据
computed:{
// total计算属性
// 特点:有缓存,当修改商品数量的时候,会在上次结果的基础上再次计算
// 只有计算属性里面的缓存的属性发生变化的时候,total才会再次执行
// total是自定义属性
total(){
var total=0
this.list.forEach(e => {
total+=e.price*e.num
});
return total
}
}
})
</script>