直接上代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1 class="price">{{priceToFixedByComputed}}</h1>
<h1 class="price">{{priceToFixedByMethods()}}</h1>
<h1 class="price">{{price | priceToFixedByFilters}}</h1>
<h2 class="price">{{priceToFixedByComputed}}</h2>
<h2 class="price">{{priceToFixedByMethods()}}</h2>
<h2 class="price">{{price | priceToFixedByFilters}}</h2>
<h3 class="price">{{priceToFixedByComputed}}</h3>
<h3 class="price">{{priceToFixedByMethods()}}</h3>
<h3 class="price">{{price | priceToFixedByFilters}}</h3>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data() {
return {
price: 27.999999999
}
},
computed: {
priceToFixedByComputed() {
console.log('computed')
return this.price.toFixed(2)
}
},
methods: {
priceToFixedByMethods() {
console.log('methods')
return this.price.toFixed(2)
}
},
filters: {
priceToFixedByFilters(val) {
console.log('filters')
return val.toFixed(2)
}
},
watch: {
price(val) {
console.log('watch')
}
},
})
</script>
</body>
</html>
computed贱纠,一般用于計(jì)算,可直接在模板中使用有緩存機(jī)制响蕴,性能比methods更高谆焊。
image.png
如上圖所示,當(dāng)我多次調(diào)用在表達(dá)式中使用price時(shí)换途,computed只計(jì)算一次懊渡,計(jì)算完后只要參數(shù)不改變,就不在計(jì)算军拟,緩存下來重復(fù)使用。而methods和filters只要使用到了就調(diào)用誓禁,沒有緩存懈息。
再來看看數(shù)據(jù)改變后
image.png
computed觸發(fā)一次,methods觸發(fā)三次摹恰,filter觸發(fā)三次辫继,watch觸發(fā)一次。
methods, 一般用于函數(shù)方法俗慈,在模板中使用時(shí)需加()姑宽,沒有緩存,使用一次就觸發(fā)一次闺阱。
filters炮车,一般用于格式化(時(shí)間,取整,取余等)瘦穆,使用時(shí)用 “|” 隔開,這里只是為了突出特殊場景下computed的高效性纪隙。
watch,當(dāng)觀察的對象改變時(shí)觸發(fā)扛或,沒有返回值绵咱。