Vue组件实现购物车练习(ts)

课后练习实现如图所示购物车功能,使用vue、typescript实现 

结构如下:

Body.vue

<template>
    <div>
        <table>
            <tr v-for="item in goods" key="item.id">
                <th><img :src="getImageUrl(item.img)" class="img" /></th>
                <th class="name">{{ item.name }}</th>
                <th class="name"><button @click="item.num > 0 ? item.num-- : 0">-</button>
                    <input type="text" v-model="item.num" class="text">
                    <button @click="item.num++">+</button>
                </th>
                <th class="name"><a @click="delGoods(item.id)">移出购物车</a></th>
            </tr>
        </table>
    </div>
    <div class="bottom">
        总价:{{ getTotalPrice }}
        <button style="margin-right: 25px;">结算</button>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

const goods = ref([
    { id: 1, name: "TCL彩电", num: 1, img: "a", price: 180 },
    { id: 2, name: "机顶盒", num: 1, img: "b", price: 180 },
    { id: 3, name: "海尔冰箱", num: 1, img: "c", price: 248 },
    { id: 4, name: "小米手机", num: 1, img: "d", price: 260 },
    { id: 5, name: "PPTV电视", num: 2, img: "e", price: 124 },
])
const getImageUrl = (name: string) => {
    const ref = new URL(`../assets/img/${name}.jpg`, import.meta.url).href
    return ref
}
const delGoods = (id: number) => {
    const index = goods.value.findIndex(item => {
        return item.id === id
    })
    goods.value.splice(index, 1)
}
const getTotalPrice = computed(() => {
    let totalPrice = 0
    for (let i = 0; i < goods.value.length; i++) {
        totalPrice = totalPrice + goods.value[i].price * goods.value[i].num
    }
    return totalPrice
})
</script>

<style scoped>
.img {
    width: 50px;
    height: 50px;
    line-height: 30px;
}
.name {
    width: 100px;
    height: 30px;
    text-align: center;
    line-height: 30px;
}
.text {
    width: 30px;
    height: 20px;
    text-align: center;
    line-height: 20px;
}
.bottom {
    background-color: rgb(141, 83, 196);
    text-align: right;
    line-height: 40px;
    width: 360px;
    height: 40px;
}
</style>

Header.vue 

<script setup lang="ts">
import { ref } from 'vue';

const people = ref({
    name: "张三"
})
</script>

<template>
    <div class="header">
        {{ people.name }}的商品
    </div>
</template>

<style scoped>
.header {
    background-color: blueviolet;
    text-align: center;
    line-height: 40px;
    width: 360px;
    height: 40px;
}
</style>

App.vue 

<script setup lang="ts">
import Header from './components/Header.vue'
import Body from './components/Body.vue'
</script>

<template>
    <div>
        <Header />
    </div>
    <div>
        <Body />
    </div>
</template>

(其实少了个底部bottom的组件!把功能写到了Body里面,直接在Body里实现的,老师讲了之后懒得修改啦,先酱紫叭~)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值