温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用vue.js怎么实现一个购物车添加商品组件

发布时间:2021-05-20 18:00:40 来源:亿速云 阅读:516 作者:Leah 栏目:web开发

今天就跟大家聊聊有关使用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);     }

看完上述内容,你们对使用vue.js怎么实现一个购物车添加商品组件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI