【Vue3】用computed進行計算處理

Vue3

【Vue3】用computed進行計算處理

Vue3


getter、setter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<div id="app">
  <ul>
    <li v-for="product in products">
      {{ product.name }} / {{ product.price }}
      <button type="button" @click="addToCart(product)">加入購物車</button>
    </li>
  </ul>
  <h6>購買清單:</h6>
  <ul>
    <li v-for="cart in carts">
      {{cart.name}}
    </li>
  </ul>
  <p>老闆直接給優惠價:</p>
  <input type="text" v-model="num">
  <button type="button" @click="total = num">更新</button>
  <p>總計:{{ `NT$ ${total}` }}</p>
</div>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Vue.createApp({
  data(){
    return{
      num: "",
      products:[
        {
          name: '蛋餅',
          price: 30,
          vegan: false
        },
        {
          name: '飯糰',
          price: 35,
          vegan: false
        },
        {
          name: '小籠包',
          price: 60,
          vegan: false
        },
        {
          name: '蘿蔔糕',
          price: 30,
          vegan: true
        },
      ],
      carts:[],
      sum: ""
    }
  },
  methods:{
    addToCart(product){
      this.carts.push(product);
    }
  },
  computed:{
    total:{
      get(){
        let total = 0;
        this.carts.forEach((item)=>{
          total += item.price;
        })
        return this.sum || total
      },
      set(val){
        this.sum = val;
      }
    }
  }
}).mount("#app");

get會自動接收傳入的值進行計算,set會將值更新到data

Vue3 

其他相關