<div id="app">
  <div class="p-5">
    <div id="app">
      <h3>使用 methods 處理複雜資料</h3>
      <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="item in carts">{{ item.name }}</li>
      </ul>
      總金額 {{ sum }}
      <h3>作為 $filter 使用(取代複雜表達式)</h3>
      總金額 {{ convertToAmount(sum) }}
    </div>
  </div>
</div>
const App = {
  data() {
    return {
      num: 10,
      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: {
    trigger(name) {
      console.log(name, '此事件被觸發了')
    },
    callOtherMethod() {
      this.trigger('由 callOtherMethod 觸發')
    },
    methodParameter(a, b, c, d) {
      console.log(a, b, c, d)
    },
    addToCart(product) {
      this.carts.push(product)
      this.calculate();
    },
    calculate() {
      let total = 0;
      this.carts.forEach(item => {
        total += item.price;
      });
      this.sum = total;
    },
    convertToAmount(price) {
      return `NT$ ${price}`;
    }
  },
  created() {
    this.trigger('由生命週期觸發');
  }
};
Vue.createApp(App).mount('#app');
Run Pen

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.global.prod.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js