<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
总价格为:{{AutoPrice3}}
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue ({
el : '#app',
computed:{
AutoPrice:function(){
let sumPrice=0;
for(let i=0;i<this.books.length;i++){
sumPrice+=this.books[i].price;
}
return sumPrice;
},
//多种for循环
//for(let i in this.books)
//for(let book of this.books)
AutoPrice2: function(){
let sumPrice=0;
for(let i in this.books){
sumPrice+=this.books[i].price;
}
return sumPrice*10;
},
AutoPrice3: function(){
let sumPrice=0;
for(let book of this.books){
sumPrice+=book.price;
}
return sumPrice;
}
},
data: {
books:[
{id:1,name:'小说1',price:119},
{id:2,name:'小说2',price:130},
{id:3,name:'小说3',price:200}
]
}
})
</script>
</body>
</html>
02:get 和set操作
其实我们在使用 computed操作的时候,是自动调用了get的方法,并且computed相比较method是有缓存的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue ({
el : '#app',
data: {
firstName: 'FirstName',
lastName: 'lastName'
},
computed: {
fullName: {
set:function (newValue){
console.log("--------set------------");
console.log(newValue);
let names=newValue.split(" ");
console.log(names);
this.firstName=names[0];
this.lastName=names[1];
},
get: function(){
return this.firstName+"--------"+this.lastName
}
}
}
//computed和methods区别
//methods方法,方法掉几次就会执行几次方法,效率比较低下
//computed函数:只要 调的元素值不会发生变化,只会执行一次。但当值发生改变的时候,会重新调用一次该函数
//computed 效率高,会有缓存的原因存在
})
</script>
</body>
</html>