<div id="app">
<div class="p-5">
<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>
<h3>Computed Getter, Setter</h3>
sum 的值:
<input type="number" v-model.number="num">
<button type="button" @click="total = num">更新</button>
total 的值:{{ total }}<br>
sum 的值:{{ sum }}
</div>
</div>
const App = {
data() {
return {
num: 0,
search: '',
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: {
get() {
let total = 0;
this.carts.forEach(item => {
total += item.price;
});
return this.sum || total;
},
set(val) {
// 透過事件將input內的值(num)傳到total setter的val上,並且存回data內
this.sum=val;
}
},
}
};
Vue.createApp(App).mount('#app');