【VUE学习】购物车案例
本帖最后由 Dexlux 于 2021-4-2 17:24 编辑<!DOCTYPE html>
<html lang="en">
<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>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
table {
margin: 100px auto;
border-collapse: collapse;
border-color: #9e9898;
text-align: center;
}
thead {
background-color: #ccc;
}
td {
width: 100px;
height: 50px;
padding: 10px;
}
.num button {
padding: 0 5px;
}
</style>
</head>
<body>
<div id="app">
<span v-if="books.length == 0">
购物车为空
</span>
<table border="1" v-else>
<thead>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.birth}}</td>
<td>¥{{item.price.toFixed(2)}}</td>
<td class="num"><button @click='add(index)'>↑</button>{{item.count}}<button @click='sub(index)'
:disabled='item.count == 0'>↓</button>
</td>
<td><button @click='remove(index)'>移除</button></td>
</tr>
<td><span>总价:${{total.toFixed(2)}}</span></td>
</tbody>
</table>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{
name: '算法导论',
birth: '2006-9',
price: 85.00,
count: 1
},
{
name: 'UNIX编程艺术',
birth: '2006-2',
price: 59.00,
count: 1
},
{
name: '编程珠玑',
birth: '2008-10',
price: 39.00,
count: 1
},
{
name: '代码大全',
birth: '2006-3',
price: 128.00,
count: 1
}
]
},
computed: {
total() {
// let total = 0;
// for (let i = 0; i < this.books.length; i++) {
// total += this.books.price * this.books.count;
// }
// return total;
return this.books.reduce(function (pre, book) {
return pre + book.price * book.count;
}, 0)
}
},
methods: {
add(index) {
if (this.books.count >= 0) {
++this.books.count;
} else {
this.books.count = 0;
}
},
sub(index) {
if (this.books.count > 0) {
--this.books.count;
} else {
this.books.count = 0;
}
},
remove(index) {
this.books.splice(index, 1);
}
}
})
</script>
</html> 别人的东西也好意思发出来???? yn9 发表于 2021-4-2 19:04
别人的东西也好意思发出来????
词典里的字也敢打出来????? 课程布置的案例我自己打出来我不能分享??? 好需要这个,原帖在哪? 裂焰 发表于 2021-4-28 00:36
好需要这个,原帖在哪?
https://www.bilibili.com/video/BV15741177Eh?p=41
这个 谢谢你了 好像有点少哇
页:
[1]