课后练习实现如图所示购物车功能,使用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里实现的,老师讲了之后懒得修改啦,先酱紫叭~)