20-0 js
const App = {
data() {
return {
num: 10,
search: '',
products: [
{
name: '蛋餅',
price: 30,
vegan: false
},
{
name: '飯糰',
price: 35,
vegan: false
}
],
carts: [],
sum: 0,
}
},
computed:{
total(){
let total = 0;
this.carts.forEach(item => {
total += item.price;
});
return total
},
filterProducts(){
return this.products.filter(item=>{
console.log(item)
return item.name.match(this.search);
})
}
},
methods: {
addToCart(product) {
this.carts.push(product)
},
},
created() {
console.log(this);
}
};
Vue.createApp(App).mount('#app');
20-1 使用computed方法將購買總額顯示畫面上
<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>
<!-- 使用 computed方法的total() -->
total 的值:{{ total }}<br>
20-2 Computed 常見技巧 - 搜尋
<input type="search" v-model="search">
<ul>
<li v-for="item in filterProducts">
{{ item.name }} / {{ item.price }}
</li>
</ul>
.
知識點來源:六角課程
以上是今天所提供知識點如有誤,再請務必在下面留言~