什么是計算屬性
模板內的表達式非常便利,但是設計它們的初衷是用于簡單運算的。在模板中放入太多的邏輯會讓模板過重且難以維護。例如:
<div id="example"> {{ message.split('').reverse().join('') }}</div>
這里的表達式包含3個操作,并不是很清晰,所以遇到復雜邏輯時應該使用Vue特帶的計算屬性computed來進行處理。
計算屬性(computed)用于處理復雜邏輯
computed:{}
computed做為vue的選項是固定的
例子:
<div id="itany"> <p>{{mes}}</p> <p>{{count}}</p></div><script src="../js/vue.js"></script><script> new Vue({ el:'#itany', data:{ mes:'hello vue' }, computed:{ count:function(){ //切割 翻轉 拼接 return this.mes.split(' ').reverse().join('---') } } })</script>
輸出結果為:
hello vue
vue---hello
練習
要求:點擊button按鈕使數字以對應的價格改變
Image 2.png
代碼如下:
<div id="itany"> <button v-on:click="num">總和</button> <p>{{arr}}</p></div><script src="../js/vue.js"></script><script> new Vue({ el:'#itany', data:{ name:{price:2,count:0}, names:{price:4,count:0}, see:true }, methods:{ num:function(){ this.name.count++, this.names.count++ } }, computed:{ arr:function(){ return this.name.price*this.name.count+this.names.price*this.names.count } } })</script>
新聞熱點
疑難解答