# Computed 運算基礎運用 ex. 搜尋 (3-2)
###### tags: `Vue`、`3. Options API`
2022.3.3
  Computed用來做隨時監聽動 (例如:匯率),當Computed中的資料有變化時,系統會自動跑computed程式。
### 1. 一般模式(「預設為Gatter」 只有取值,沒有寫入)
#### 範例1 : 計算購物車總金額
```
<ul>
<h2>商品列表</h2>
<li v-for="item in products" :key="item.name">
{{ item.name }} / {{ item.price}} 元
<button @click="addcart(item)"> 加入購物車 </button>
</li>
<h2>購物車</h2>
<li v-for="item in carts" :key="item.name">
{{ item.name }} / {{ item.price}} 元
</li>
<h3>總金額: {{ total }}</h3>
</ul>
<script>
data(){
return{
products:[
{name:'商品1',price:100},
{name:'商品2',price:200},
{name:'商品2',price:300}
],
carts:[]
}
},
computed:{
total(){
let total = 0;
this.carts.forEach(function(item){
total+=item.price;
})
return total
},
},
methods:{
addcart(item){
this.carts.push(item);
}
}
</script>
```
#### 範例2 : 常見技巧-搜尋
```
<ul>
<h2> 搜尋 <h2>
<input type="search" v-model="search">
<li v-for="item in productfileter" :key="item.name">
{{ item.name }} / {{ item.price }} 元
</li>
<ul>
<script>
data(){
return{
product : [
{name:'玉米蛋餅' , price:30},
{name:'火腿蛋餅' , price:40},
{name:'起司蛋餅' , price:20}
],
search : '',
}
},
computed:{
productfileter(){
return this.product.filter((item)=>{
return item.name.match(this.search)
})
},
}
</script>
```
### 2. Getter 與 Setter 模式
* Getter : 只有取值,沒有寫入。
* Setter : 能對數據進行更改,並寫入。
```
原價 : {{ or_price }} 元 <p>
折扣後 : {{ new_price }} 元 <p>
折扣 : <input type="number" v-model.number = "discount"> 折
<button @click="do_discount=discount">確認</button>
<script>
data(){
return{
or_price: 100,
new_price: 0,
discount : 0,
}
},
computed:{
do_discount:{
get(){
//讀取值,並return渲染
},
set(val){
this.new_price = (val/10) * this.or_price
}
}
}
</script>
```