<div id="app">
<div class="p-5">
<h3>Computed 將目前的數值運算呈現至畫面上</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>
total 的值:{{total}} <br>
</div>
</div>
const App = {
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: {
total() {
let total = 0;
this.carts.forEach(item => {
total += item.price;
});
return total;
}
}
};
Vue.createApp(App).mount('#app');