blog

Vue Scaffolding Series 03 - ショッピングカートの操作

1.ショッピングカートの操作をシミュレートする App.vue - 親コンポーネント カートコンポーネントを導入し、それにリストデータを渡す カートコンポーネント - cart.vue 知識ポイントの...

Nov 1, 2020 · 3 min. read
シェア

1.ショッピングカート操作のシミュレーション

  • App.vue---

    • カートコンポーネントを導入し、リストデータを渡します。
//App.vue
<template>
 <div id="app">
 <ul>
 <li v-for="(item,index) in cartList" :key="index">
 <h3>{{item.title}}</h3>
 <p>{{item.price}}</p>
 </li>
 </ul>
 <my-cart :cart="cartList" :title="title"></my-cart>
 </div>
</template>
<script>
import myCart from "./components/Cart";
export default {
 name: 'App',
 components: {
 myCart,
 },
 data() {
 return {
 cartList:[
 {id:1,title:"vue実用的な開発 ",price:996,active:true,count:1},
 {id:2,title:"es6実用的な開発 ",price:998,active:true,count:1},
 {id:3,title:"python実用的な開発 ",price:920,active:true,count:1},
 {id:4,title:"react実用的な開発 ",price:123,active:true,count:1}, 
 ],
 title:"ショッピングカート"
 }
 },
}
</script>
<style>
#app {
 font-family: Avenir, Helvetica, Arial, sans-serif;
}
</style>
  • ruduceメソッドの使用に注意:
<template>
 <div>
 <h2>{{title}}</h2>
 <table border="1">
 <tr>
 <th>#</th>
 <th> </th>
 <th> </th>
 <th>数量:</th>
 <th> </th>
 </tr>
 <tr v-for="(item,index) in cart" :key="index">
 <td >
 <input type="checkbox" v-model="item.active"> 
 </td>
 <td>{{item.title}}</td>
 <td>{{item.price}}</td>
 <td>
 <button @click="reduc(index)">-</button>
 {{item.count}}
 <button @click="add(index)">+</button>
 </td>
 <td>
 ¥{{item.price*item.count}}
 </td>
 </tr>
 <tr>
 <td></td>
 <td colspan="2">{{activeCount}}/{{count}}</td>
 <td colspan="2">{{allCount}}</td>
 </tr>
 </table>
 </div>
</template>
<script>
export default {
 name:"cart",
 props:["title","cart"],
 data() {
 return {
 }
 },
 methods: {
 remove(i){
 if(window.confirm("本当に削除しますか?")){
 this.cart.splice(i,1);
 }
 },
 reduc(i){
 let count = this.cart[i].count;
 count >1 ? this.cart[i].count -=1 : this.remove(i)
 },
 add(i){
 this.cart[i].count+=1;
 }
 },
 computed: {
 count(){
 return this.cart.length;
 },
 activeCount(){
 return this.cart.filter(v=>v.active).length;
 },
 activeitem(){
 return this.cart.filter(v=>v.active);
 },
 allCount(){
 // console.log(this.activeitem)
 // let sum=0;
 // this.activeitem.forEach(item => {
 // // if(item.active){
 // sum += item.price * item.count
 // // }
 // });
 // return sum;
 return this.cart.reduce((sum,c)=>{
 if(c.active){
 sum += c.price * c.count
 }
 return sum;
 },0); 
 }
 },
}
</script>
<style scoped>
table{
 text-align: center;
}
</style>

知識ポイントの要約:

  • ルドゥーチェ法の使用に注意してください。
  • 例えば、allCountのthis.activeitemを経由して
Read next