博客列表 >Vue自学:使用vue做一个简单的购物车

Vue自学:使用vue做一个简单的购物车

梁凯达的博客
梁凯达的博客原创
2021年01月14日 08:35:30783浏览

<!DOCTYPE html>

<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>作业案例:图书网站的购物车页面</title>
<style type="text/css">
table {
width: 700px;
height: 300px;
border: 1;
}

td {
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<div id="on" v-if="books.length">
<table border="" cellspacing="0" cellpadding="0">
<thead>
<td>序号</td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</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(item.price)}}
</td>
<td>
<button v-on:click="cut_click(index)" v-bind:disabled="item.count<=1">-</button>
{{item.count}}
<button v-on:click="add_click(index)">+</button>
</td>
<td>
<button type="button" v-on:click="rmove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h1>合计金额为:{{commodityCount | showPrice}}</h1>
</div>
<div v-else>
购物车为空
</div>
</div>
</body>
<script type="text/javascript">
//重要知识点
// toFixed(’num’)给数字保留后两位小数 toFixed(‘要保留几位就填写几位’)
// 对象内数组写法 data{books[{key:value,key:value}]}
// splice(index,1) :从第一个开始,删除掉1个
// filters()过滤器的使用作用,是让其他的内容可以复用过滤器内的格式
// v-bind:disabled,设置布尔值true或false
// 移除按钮,只需要数组当中的某个键值对移除接口,传递索引值
// 可以使用V-if、V-else的方式,帮助div实现隐藏和展示
const app = new Vue({
el: ‘#app’,
//用对象的方式写数组,在对象内出传递了一个数组
data: {
books: [{
id: 1,
name: ‘<<算法导论>>’,
date: ‘2020-06’,
price: 3,
count: 1
},
{
id: 2,
name: ‘<<算法导论>>’,
date: ‘2020-06’,
price: 3,
count: 1
},
{
id: 3,
name: ‘<<算法导论>>’,
date: ‘2020-06’,
price: 3,
count: 1
},
{
id: 4,
name: ‘<<算法导论>>’,
date: ‘2020-06’,
price: 3,
count: 1
},
],
},
methods: {
add_click(index) {
this.books[index].count++
},
cut_click(index) {
this.books[index].count—
},
rmove(index) {
this.books.splice(index, 1)
}
},
//计算属性
computed:{
//计算总商品价格
commodityCount(){
commodityCount = 0;
for(let i =0;i<this.books.length;i++){ commodityCount += this.books[i].price*this.books[i].count } return commodityCount } }, //过滤器 filters: { showPrice(price) { return '¥' + price.toFixed(2) } } }) </script>
</html>

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议