关于购物车订单计算
关于购物车订单计算,我写了一个函数,但不知道在setup函数里要如何调用,使用其执行结果。
我写的函数如下:
相关代码:
const SummaryCartEffect = () => {
const store = useStore();
const route = useRoute();
const shopId = route.params.id;
const { cartList } = reactive(store.state);
const goodsList = cartList[shopId];
let totalPrice = 0;
let goodsNum = 0;
if (goodsList) {
for (let i in goodsList) {
goodsNum += goodsList[i].count;
totalPrice += goodsList[i].count * goodsList[i].price;
}
}
console.log(totalPrice, goodsNum);
return {totalPrice, goodsNum };
};
我知道我写的这个函数有没有问题,也不知道在setup里应该如何用,总之,结果不对。
之前学的函数导出的都是对象,在setup函数里,用解构赋值从函数执行结果中导出即可,但现在这个是普通数值,不知道如何用了。请老师帮忙解决一下。
44
收起
正在回答
3回答
同学你好,解答如下:
1、如果使用一个计算属性实现,此计算属性可以返回一个对象,具体操作如下:


在模板中使用:
2、不使用计算属性的话,目前这边没有找出比较好的方法。
祝学习愉快~
好帮手慕言
2021-03-05 11:55:42
同学你好,此处需要用到计算属性,按照同学的代码,可以修改如下:


修改后的js代码:
<script>
import { reactive, computed } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
const SummaryCartEffect = () => {
const store = useStore();
const route = useRoute();
const shopId = route.params.id;
const { cartList } = reactive(store.state);
// 总价
const totalPrice = computed(() => {
const goodsList = cartList[shopId];
let totalPrice = 0;
if (goodsList) {
for (let i in goodsList) {
const product = goodsList[i];
totalPrice += product.count * product.price;
}
}
return totalPrice.toFixed(2);
});
// 总数量
const goodsNum = computed(() => {
const goodsList = cartList[shopId];
let goodsNum = 0;
if (goodsList) {
for (let i in goodsList) {
const product = goodsList[i];
goodsNum += product.count;
}
}
return goodsNum;
});
return { goodsNum, totalPrice };
};
export default {
name: "Cart",
setup() {
const { goodsNum, totalPrice } = SummaryCartEffect();
return { goodsNum, totalPrice };
}
};
</script>祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星