【Vue3】點擊商品加入購物車

Vue3

【Vue3】點擊商品加入購物車

Vue3


methods方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<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>總計:{{ conversionPrice(sum) }}</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
Vue.createApp({
  data(){
    return{
      products:[
        {
          name: '蛋餅',
          price: 30,
          vegan: false
        },
        {
          name: '飯糰',
          price: 35,
          vegan: false
        },
        {
          name: '小籠包',
          price: 60,
          vegan: false
        },
        {
          name: '蘿蔔糕',
          price: 30,
          vegan: true
        },
      ],
      carts:[],
      sum: 0
    }
  },
  methods:{
    //商品加入購物車
    addToCart(product){
      this.carts.push(product)
      this.calculatePrice();
    },
    //計算購物車內的總金額
    calculatePrice(){
      let total = 0;
      this.carts.forEach((item)=>{
        total += item.price;
      })
      this.sum = total;
    },
    //轉換金額顯示格式
    conversionPrice(price){
      return `NT$ ${price}`
    }
  }
}).mount("#app");


computed方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<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>總計:{{ calculateTotal }}</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
Vue.createApp({
  data(){
    return{
      products:[
        {
          name: '蛋餅',
          price: 30,
          vegan: false
        },
        {
          name: '飯糰',
          price: 35,
          vegan: false
        },
        {
          name: '小籠包',
          price: 60,
          vegan: false
        },
        {
          name: '蘿蔔糕',
          price: 30,
          vegan: true
        },
      ],
      carts:[],
      sum: 0
    }
  },
  methods:{
    addToCart(product){
      this.carts.push(product)
    }
  },
  computed:{
    calculateTotal(){
      let total = 0;
      this.carts.forEach((item)=>{
        total += item.price;
      })
      this.sum = total;
      return `NT$ ${total}`
    }
  }
}).mount("#app");

Vue3 

其他相關