欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > vue中reduce属性的使用@3@

vue中reduce属性的使用@3@

2025/2/24 0:56:02 来源:https://blog.csdn.net/qq_34953053/article/details/142179552  浏览:    关键词:vue中reduce属性的使用@3@
 1.reduce方法

​ reduce方法的使用(数组方法): 遍历数组,求和

​ 语法:数组名.reduce((pre,current) => {},参数2)

​ pre:上次执行该方法的返回值

​ current:数据项

​ 实例代码:

let shoppingCart = [{name: 'Vuejs入门', price: 99, count: 3},{name: 'Vuejs底层', price: 89, count: 1},{name: 'Vue从入门到放弃', price: 19, count: 5},
];let totalPrice = shoppingCart.reduce((total, item) => {console.log(total,item.price) // return total + item.price * item.count;
}, 0); // 初始值为0,表示从第一个元素开始累加console.log(totalPrice); // 输出总价:481// 第一个console.log打印的 0 99 297 89 386 19 // 第二个console.log打印的 输出总价:481
2.Vue的计算属性

存放属性(以函数的形式)

当一个值受其他值影响的时候,就会将这个值写在计算属性当中

有效缓存效果:只执行一次

在Vue模板中,你可以将这个计算属性绑定到一个数据属性上,以便在页面上显示:

<div id="app"><p>总价: {{ totalPrice }}</p>
</div><script>new Vue({el: '#app',{shoppingCart: [ /* ...购物车数据... */ ]},computed: {totalPrice() {return this.shoppingCart.reduce((total, item) => {return total + item.price * item.count;}, 0);}}});
</script>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词