1.计算属性 computed有两个特点
1)必须要有return值
2)当计算属性所依赖的数据发生改变时,就会自动调用
3)使用时和data中的属性使用方法一样
4)可以定义多种计算属性
<body>
<div id="app">
<input type="text" placeholder="请输入数量" v-model="num">
<input type="text" placeholder="请输入价格" v-model="price">
总价值:methods得到的值<p>{{allPrice()}}</p>
总价值:computed得到的值<p>{{getAllPrice}}</p>
</div>
</body>
<script>
new Vue({
el: "#app",
data: {
num: 10,
price: 10
},
methods: {
allPrice() {
let allPrice = this.num * this.price
return allPrice
}
},
//计算属性
computed: {
getAllPrice() {
let getAllPrice = this.num * this.price
return getAllPrice
}
},
})
</script>
2.mothods方法和computed计算属性的区别
1)methods方法依赖于页面渲染,只要页面发生渲染methods就会重新调用
2)computed计算属性依赖于浏览器缓存,只用于当其依赖的数据发生改变时才会重新调用
3)computed必须要有return值