vue.js購物車添加商品組件

現實向購物車添加商品組件

代碼
<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);

        }     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章