vue备忘录-购物车案例

Carts.vue

<template>
    <div>
        <h2>购物车</h2>
        <ul>
            <li v-for="item,index of fruits" :key="index" >{{item.name}} 价格:{{item.price}}
                 <ControlsA :num="item.num" :index="index" @add="add" @sub="sub"></ControlsA>
            </li>
        </ul>
    </div>
</template>
<script>
import ControlsA from "./ControlsA.vue"
export default {
    data(){
        return{
            fruits:[
                {name:"apple",price:3.2,num:0},
                {name:"pineapple",price:3.4,num:1},
                {name:"banana",price:3.0,num:2}
            ]
        }
    },
    components:{ControlsA},
    methods:{
        add(index){
            this.fruits[index].num++
        },
        sub(index){
            if(this.fruits[index].num>0){
                this.fruits[index].num--
            }
        }
    }
}
</script>

ControlsA.vue

<template>
    <div>
        <!-- 是carts的子组件 -->
        <button @click="sub">-</button>{{num}}
        <button @click="add">+</button>
    </div>
</template>
<script>
export default {
    props:["num","index"],
    methods:{
        add(){
            this.$emit("add",this.index)//this.index
        },
        sub(){
            this.$emit("sub",this.index)
        }
    }
}
</script>

App.vue

<template>
  <div>
    <CartsA></CartsA>
  </div>
</template>

<script>
import CartsA from "./components/CartsA.vue"
export default {
 components:{CartsA}
}
</script>
上一篇:函数的属性和行为使用


下一篇:Java:外卖团购系统