Fetch the repository succeeded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue练习02-购物车案例</title>
<style>
table {border: 1px solid #e9e9e9;border-collapse: collapse;border-spacing: 0;}
th, td {padding: 8px 16px;border: 1px solid #e9e9e9;text-align: left;}
th {background-color: #f7f7f7;color: #5c6b77;font-weight: 600;}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showprice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increament(index)">+</button>
</td>
<td><button @click="removeHandle(index)">删除</button></td>
</tr>
</tbody>
</table>
<h4>总价格:{{totalPrice | showprice}}</h4>
</div>
<div v-else>购物车为空</div>
</div>
<!--<script src="../vue.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue ({
el: '#app',
data: {
books: [
{
id: 1,
name: '代码大全',
price: 89.02,
date: '2005/10/02',
count: 2
},
{
id: 2,
name: 'Js基础',
price: 60.22,
date: '2006/02/20',
count: 1
},
{
id: 3,
name: 'html基础',
price: 59.3,
date: '2015/05/12',
count: 4
},
{
id: 4,
name: 'css基础',
price: 39.09,
date: '2003/12/15',
count: 5
},
{
id: 5,
name: 'vue进阶',
price: 29.54,
date: '2006/02/27',
count: 3
}
]
},
methods: {
// getFinalPrice(price){
// return '¥'+price.toFixed(2)
// }
increament(index){
this.books[index].count++
},
decrement(index){
this.books[index].count--
},
removeHandle(index){
this.books.splice(index,1)
}
},
computed: {
// 计算总价格函数
totalPrice(){
// let totalPrice = 0
// 1.普通的for循环方式
// for(let i=0; i < this.books.length; i++){
// totalPrice += this.books[i].price * this.books[i].count
// }
// return totalPrice
// 2.for in 方式
// for (let i in this.books){
// totalPrice += this.books[i].price * this.books[i].count
// }
// return totalPrice
// }
// 3.for of 方式
// for (let item of this.books){
// totalPrice += item.price * item.count
// }
// return totalPrice
// }
// 4.reduce高阶函数方法
return this.books.reduce(function(pre,n){
return pre + n.price * n.count
},0)
}
},
filters: {
// 使用过滤器
showprice(price){
// 使得价格保留两位小数
return '¥ '+price.toFixed(2)
}
}
})
// 补充:函数式编程(第一公民:函数)
//三个高阶函数:filter/map/reduce
</script>
</body>
</html>
Sign in to post a comment
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
Comment ( 0 )