vuejs仿美团,饿了么项目之——商品数量加减篇

首先,新增个商品数量的加减功能组件,就叫cartcontrol.vue吧。新增个底部购物车组件,叫shopcart.vue吧。在good.vue中引入并注册组件。

import cartcontrol from '../cartControl/cartcontrol.vue'
import shopcart from '../shopcart/shopcart.vue'
components:{
            cartcontrol,
            shopcart
        },
  1. cartcontrol组件在good.vue的DOM中跟每个商品名称,单价是同个级别的。绑定个属性listItem来传入遍历的list对象。
<li class="food-item food-list-hook" v-for="(item,index) in food">
    <h3>{{item.name}}</h3>
    <div class="food-detail" v-for="list in item.detail">
        <div class="title">{{list.name}}</div>
        <div class="price">{{list.price + '元'}}</div>
                        <!-- 加减号 -->
        <div class="cartcontrol-wrapper">
          <cartcontrol :listItem="list"></cartcontrol>  
        </div>
    </div>
</li>

cartcontrol.vue中,通过props来接收list对象

props: {
    listItem: {
        type: Object
    }
},

因为我在json中没有设置数量这个key,所以需要全局用vue.set进行注册这个属性。在add方法中,如果没有这个属性,那么就注册,如果有,那么就count++

    import Vue from 'vue'
    export default {
        props: {
            listItem: {
                type: Object
            }
        },
        methods: {
            decrease() {
                this.listItem.count--
            },
            add() {
                if(!this.listItem.count){
                    Vue.set(this.listItem, "count", 1)
                }else{
                    this.listItem.count++
                }
            }
        }

    }

这里增加了一点小效果。应用了<transition>。 并且当数量减到0的时候。通过v-show来控制减号和数值是否显示。

<template>
    <div class="cartcontrol">
        <transition name="roll">
            <div class="decrease" @click="decrease()" v-show="listItem.count">-</div>       
        </transition>
        <div class="count" v-show="listItem.count">{{listItem.count}}</div>
        <div class="add" @click.stop.prevent="add()">+</div>
    </div>
</template>
<style>
.cartcontrol {
    
}
.count {
    display: inline-block;
    font-size: 14px
}
.decrease, .add {
    display: inline-block;
    border:1px solid #000;
    border-radius: 50%;
    font-size: 14px;
    width: 14px;
    height: 14px;
    text-align: center;
    line-height: 12px;
}
.roll-enter-active, .roll-leave-active {
    transition: .5s all linear
}
.roll-enter, .roll-leave-to {
    transform: translateX(20px) rotate(180deg) ;
}
</style>

写的比较粗糙,估计只有我自己能懂。这里要注意一下,在BScroll实例中要配置下click:true。使better-scroll滚动部分支持点击事件。否则加减号的点击事件无效。好吧~下篇写下底部的购物车功能。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容