語法:
計算屬性:computed:{
變量名:function (){
...處理
return 返回值;
}
}
方法:
methods:{
方法名:function(){
...處理
可返回值也可以不返回
}
}
監聽器
watch:{
被監聽屬性:function(){
屬性改變時處理...
}
代碼如下:想看結論直接往下拉
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue的計算屬性,方法,監聽器</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<h1>{{num1}}</h1>
<h1>{{num2}}</h1>
<h1>{{numz}}</h1>
<h1>{{total}}</h1>
<h1>{{total1()}}</h1>
<h1>{{total2}}</h1>
</div>
<script>
var app = new Vue({
el:'#app2',
data:{
num1:0,
num2:0,
numz:666,
total2:0,
},
//計算屬性返回值實現
computed:{
total:function (){
console.log("計算了一次1");
return this.num1+this.num2;s
}
},
//方法實現
methods:{
total1:function(){
console.log("計算了一次2");
return this.num1 + this.num2;
}
},
//監聽器實現
watch:{
num2:function(){
console.log("計算了一次3");
this.total2 = this.num1+this.num2;
},
num1:function(){
console.log("計算了一次3");
this.total2 = this.num1+this.num2;
}
},
});
</script>
</body>
</html>
頁面效果與測試如下
結論:
剛加載頁面的時候調用了方法與計算屬性
修改了無關變量時,因爲計算屬性與監聽有緩存而方法沒有,所以
修改了相關變量時,緩存重置,重新計算
由此可以看出此場景時 計算屬性最好用,既簡潔又有緩存