结果图
实现步骤
1.在界面上以表格的形式,显示一些书籍的数据;
2.在底部显示书籍的总价格;
3.点击+或者-可以增加或减少书籍数量(如果为1,那么不能继续-);
4.点击移除按钮,可以将书籍移除(当所有的书籍移除完毕时,显示:购物车为空~);
文件结构:
代码示例
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="app">
<template v-if="books.length">
<table >
<thead >
<tr>
<th>序号</th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody v-for="(item,index) in books" :key="item.id">
<tr>
<td>{{index+1}} </td>
<td>{{item.name}} </td>
<td>{{item.date}}</td>
<td>{{ formatPrice(item.price)}}</td>
<td> <button :disabled="item.count<=1" @click="decrement(index,item)">-</button>
{{item.count}}
<button @click="increment(index,item)">+</button></td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{ formatPrice(totalPrice)}}</h2>
</template>
<template v-else>
<h2>购物车为空, 请添加商品~</h2>
</template>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="./data.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
books: books
}
},
computed:{
totalPrice(){
/* let p=0
for(const item of this.books){
p+=item.price*item.count
}
return p */
return this.books.reduce( (preValue,item)=>{
return preValue+item.price*item.count},0 )
}
},
methods:{
formatPrice(price){
return '¥'+price
},
increment(index,item){
item.count++
},
decrement(index,item){
item.count--
},
remove(index){
this.books.splice(index,1)
}
}
})
app.mount('#app')
</script>
</body>
</html>
data.js数据
const books = [
{
id: 1,
name: '《数据库》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《数电》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《计算机组成原理》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《多媒体技术》',
date: '2006-3',
price: 128.00,
count: 1
},
]