购物车主要实现了全选,增加商品数量,总计等功能。
相关代码:
<template>
<div id="body">
<div class="app-container">
<Header></Header>
<!-- <h1>App 根组件</h1> -->
<Goods v-for="item in list"
:key="item.id"
:title="item.goods_name"
:state="item.goods_state"
:pic="item.goods_img"
:price="item.goods_price"
:id="item.id"
:count="item.goods_count"
@state_change="getNewState">
</Goods>
<Footer :getfullState="fullState" :sum="getSum" @fullstate_change="getstate_change"></Footer>
</div>
</div>
</template>
<script>
// 导入header组件
import Header from './components/Header/Header.vue'
// 导入axios,请求数据
import axios from 'axios'
// 导入商品组件
import Goods from './components/Goods/Goods.vue'
// 全选与单价
import Footer from './components/Footer/Footer.vue'
// 导入bus
import bus from './components/eventBus'
export default {
computed:{
fullState(){
// return this.list.every(item =>item.goods_state)
// 双箭头函数后面的函数体不需要小括号
return this.list.every((item) => item.goods_state===true)
},
// 计算总价
getSum(){
return this.list
.filter((item) =>item.goods_state)
// reduce函数要有一个初始值
.reduce((sum,item)=>(sum+=item.goods_price*item.goods_count),0)
}
},
data(){
return{
list:[]
}
},
components:{
Header,
Goods,
Footer
},
methods:{
// 实现全选功能
// 发送请求,获取数据
async initDemoCar(){
const {data:res}=await axios.get('https://www.escook.cn/api/cart');
if(res.status===200){
this.list=res.list;
// console.log(this.list);
}
},
// 接收子组件的数据
getNewState(e){
this.list.some((item) => {
if(e.id===item.id){
item.goods_state=e.state
return true
}
}
)
},
// 取消全选与全选
getstate_change(e){
if(e===false){
this.list.forEach((item) => item.goods_state=false)
}else{
this.list.forEach((item) => item.goods_state=true)
}
},
},
created() {
// console.log(this);
this.initDemoCar()
bus.$on('share',(val) => {
this.list.some((item) => {
if(val.id===item.id){
item.goods_count=val.value
return true
}
})
} )
bus.$on('duce',(val) => {
this.list.some((item) => {
if(item.id===val.id){
if(item.goods_count===0){
item.goods_count=0
return true
}else{
item.goods_count=val.value
return true
}
}
})
} )
},
}
</script>
<style lang="less" scoped>
#body{
display: flex;
justify-content: center;
}
.app-container {
width: 25rem;
height: 82rem;
padding-top: 45px;
padding-bottom: 50px;
}
</style>
源码链接:
链接:https://pan.baidu.com/s/1inNVF4SvCC1ajAZI4Jfe3Q
提取码:sfu9