vue.js购物车添加商品组件的方法

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

代码

<template> <div> <!--商品减一区域--> <div v-show="food.count>0"> <i></i> </div> <!--商品数量区域--> <div v-show="food.count>0">4</div> <!--商品加一区域--> <div @click="addCart"> <i></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购物车添加商品组件的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/578be1cb1abb86ef13381d42dc27b630.html