图书添加,图书删除,计算总价,表单简单验证,利用vue.js,bootstrap
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<script src="bt/js/vue.js"></script>
<link rel="stylesheet" href="bt/css/bootstrap.min.css">
<script src="bt/js/jquery.min.js"></script>
<script src="bt/js/bootstrap.min.js"></script>
<style>
table,table tr th{text-align: center}
[v-clock]{display: none}
</style>
</head>
<body>
<div v-clock id="app" class="container">
<h3 class="text-center">书籍列表</h3><br>
<table class="table table-hover">
<tr >
<th>序号</th>
<th>书名</th>
<th>作者</th>
<th>价格</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) of bookData">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.price}}</td>
<td><button class="btn" :class="btnStyle(index)" @click="del(index)">{{item.action}}</button></td>
</tr>
</table>
<h2 class="text-right">总价为:¥<span>{{getSum}}</span></h2>
<h3 class="text-center">添加书籍</h3>
<form>
<div class="form-group">
<label for="name">书名</label>
<input type="text" class="form-control" id="name" v-model.trim="name" placeholder="请填入书名">
</div>
<div class="form-group">
<label for="author">作者</label>
<input type="text" class="form-control" id="author" v-model.trim="author" placeholder="请填入作者">
</div>
<div class="form-group">
<label for="price">价格</label>
<input type="text" class="form-control" id="price" v-model.number="price" placeholder="请填入价格">
</div>
<br>
<div class="form-group">
<button type="button" class="btn btn-info form-control" @click="add()">添加</button>
</div>
</form>
</div>
</body>
</html>
<script>
new Vue({
el:'#app',
data:{
name:'',
author:'',
price:'',
bookData:[
{name:'红楼梦',author:'曹雪芹',price:99.9,action:'删除'},
{name:'西游记',author:'吴承恩',price:69,action:'删除'}
]
},
computed:{
getSum(){ //计算总价
if (this.bookData.length !== 0){
let priceArr = [];
for (let i=0;i<this.bookData.length;i++){
priceArr.push(this.bookData[i].price)
}
//Array对象下的reduce方法,求和接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值
return priceArr.reduce(function (total,price) {
return total+price
})
}else {
return 0
}
}
// getSum(){
// return this.bookData.reduce(function (total,book) {
// console.log(book);
// return total+Number(book.price)
// },0) //传递给函数的初始值
// }
},
methods:{
btnStyle(index){ //改变button的背景色
if (index%2===0){
return {'btn-success':true}
}else {
return {'btn-danger':true}
}
},
del(index){ //删除书籍
this.bookData.splice(index,1);
},
add(){ //添加书籍
if (this.name===''||this.author===''||this.price===''){
alert('书名,作者,价格均不能为空');
return false;
}
if (!isNaN(this.name)){
alert('请输入合法的书名');
return false;
}
if (!isNaN(this.author)) {
alert('请输入作者');
return false;
}
if(isNaN(this.price)){
alert('请输入合法的数字');
return false;
}
for(let i =0 ;i<this.bookData.length;i++){
if (this.bookData[i].name===this.name && this.bookData[i].author===this.author && this.bookData[i].price===this.price ){
alert('图书已存在');
return false;
}
}
this.bookData.push({name:this.name,author:this.author,price:this.price,action:'删除'});
this.name=this.author=this.price='';
}
}
})
</script>