现实向购物车添加商品组件

代码
<template>

<div class="cartcontrol">
    <!--商品减一区域-->
    <div class="reduce" v-show="food.count>0">
        <i class="icon-remove_circle_outline"></i>
    </div>
    <!--商品数量区域-->
    <div class="num" v-show="food.count>0">4</div>
    <!--商品加一区域-->
    <div class="add" @click="addCart">
        <i class="icon-add_circle"></i>
    </div>
</div>

</template>

<script>

export default {
    name: "Cartcontrol",
    props:{
        food:{
            type:Object
        }
    },
    methods:{
        //添加购物车商品数量
        addCart(ele){
            if(!ele._constructed){
                //better-scroll的派发事件scroll的event和pc端浏览器的点击事件的event有个
                // 属性区别_constructed,pc端浏览器的点击事件的event中是没有这个属性的
                return;
            }
            //一开始food中是没有商品数量count
            if(!this.food.count){
               // this.food.count = 1;count不是food对象中的属性,直接这样写,在dom渲染的时候是无法感应到count的变化
                this.$set(this.food,'count',1);
            }else{
                this.food.count++;
            }
            console.log(this.food.count);

        }
    }
}

</script>

<style scoped lang="stylus">
.cartcontrol

display flex
height .48rem
align-items center
.num
    font-size.2rem
    width .48rem
    text-align center
    color rgb(147,153,159)
.reduce,.add
    font-size .4rem
    color rgb(0,160,220)

</style>

对象中添加新的属性,如果更新此属性的值,是不会更新视图的

addCart(ele){

            if(!ele._constructed){
                //better-scroll的派发事件scroll的event和pc端浏览器的点击事件的event有个
                // 属性区别_constructed,pc端浏览器的点击事件的event中是没有这个属性的
                return;
            }
            //一开始food中是没有商品数量count
            if(!this.food.count){
                this.food.count = 1;count不是food对象中的属性,直接向food添加新属性count,
                // 当count值发生变化的时候在dom渲染的时候是无法感应到count的变化
              
            }else{
                this.food.count++;
            }
            console.log(this.food.count);

        }
        

解决方法:使用$set可以触发更新视图,这样当count发生变化的时候,$set去触发更新视图
addCart(ele){

            if(!ele._constructed){
                //better-scroll的派发事件scroll的event和pc端浏览器的点击事件的event有个
                // 属性区别_constructed,pc端浏览器的点击事件的event中是没有这个属性的
                return;
            }
            //一开始food中是没有商品数量count
            if(!this.food.count){
               // this.food.count = 1;count不是food对象中的属性,直接向food添加新属性count,
                // 当count值发生变化的时候在dom渲染的时候是无法感应到count的变化
                this.$set(this.food,'count',1);
            }else{
                this.food.count++;
            }
            console.log(this.food.count);

        }     

素素
37 声望0 粉丝