計算屬性(computed)
date屬性和computed屬性定義的值都可以直接系結在運算式中,如果某些值需要通過計算才能得到,那使用計算屬性就再合適不過了
如果頁面中需要顯示的值是兩個運算式計算才能得到,并且還有一些比較復雜的邏輯關系,我們寫在頁面上就不太合適了
如果我們直接在頁面上是這樣的:
<template>
<div id="app">
<p>{{ firstName + lastName }}</p>
</div>
</template>
<script>
export default {
data() {
return{
firstName:"小",
lastName:"曹"
}
}
}
</script>
<style>
</style>
如果使用計算屬性來實作的話
直接在computed中寫函式即可,然后在運算式中寫computed中定義的函式名即可
<template>
<div id="app">
<p>{{ name }}</p>
</div>
</template>
<script>
export default {
data() {
return{
firstName:"小",
lastName:"曹"
}
},
computed: {
name() {
return this.firstName+this.lastName
}
}
}
</script>
<style>
</style>
最后都能實作如下效果:

以上示例都還不是太清楚,我們再舉一個例子
購物清單
總價=單價 * 數量 * 打折
計算屬性會將所給值的變化,自動地給出計算結果
<template>
<div id="app">
<h1>計算屬性和監聽器</h1>
<p>單價:{{price}}</p>
<p>折扣:{{discount}}</p>
<p>數量:
<button @click="sub">-</button>
{{quantity}}
<button @click="add">+</button>
</p>
<p>總價:{{totalPrice}}</p>
</div>
</template>
<script>
export default {
data() {
return{
price:20,
quantity:0,
discount:0.5
}
},
computed: {
totalPrice() {
return this.price * this.quantity * this.discount
}
},
methods: {
add() {
this.quantity++
},
sub() {
if(this.quantity>0)
this.quantity--
}
}
}
</script>
<style>
</style>

偵聽器(監聽一個屬性的變化)
格式:
quntity(val)就等于監聽的quntity這個變數,val是監聽到的變化后的值
watch: {
quantity(val) {
this.totalPrice = this.price * val * this.discount
}
},
我們把剛才的計數器改成使用偵聽器來實作
<template>
<div id="app">
<h1>計算屬性和監聽器</h1>
<p>單價:{{price}}</p>
<p>折扣:{{discount}}</p>
<p>數量:
<button @click="sub">-</button>
{{quantity}}
<button @click="add">+</button>
</p>
<p>總價:{{totalPrice}}</p>
</div>
</template>
<script>
export default {
data() {
return{
price:20,
quantity:0,
discount:0.5,
totalPrice:0
}
},
watch: {
quantity(val) {
this.totalPrice = this.price * val * this.discount
}
},
methods: {
add() {
this.quantity++
},
sub() {
if(this.quantity>0)
this.quantity--
}
}
}
</script>
<style>
</style>
以上的例子,偵聽器也能做,計算屬性也能做,那我們什么時候應該用哪個?
計算屬性與偵聽器的對比
一個值的改變,會影響多個值(或處理多件事),使用偵聽器(性能消耗更高),
監測路由的時候只能使用監聽器來實作
(為了觀察一個值)多個值的改變,為了得到一個結果,使用計算屬性,(為了得到一個值)
實際開發中,大部分問題都可以用computed解決,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/501275.html
標籤:其他
下一篇:Vue生命周期鉤子
