使用Vue浅浅实现一个购物车小案例
<!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>
<style>
.tr {
display: flex;
justify-content: space-between;
width: 600px;
color: black;
}
.tr > th {
width: 100px;
}
</style>
</head>
<body>
<div id="app"></div>
<template id="my-app">
<h1>书籍购物车</h1>
<div>
<label for="">请输入书籍名称:</label>
<input type="text" v-model="input1" />
<p></p>
<label for="">请输入出版日期:</label>
<input type="date" v-model="input2" />
<p></p>
<label for="">请输入书籍单价:</label>
<input type="number" v-model="input3" />
<span>{{' '}}</span>
<p></p>
<button @click="addBook">添加</button>
</div>
<p></p>
<div>
<table border="1">
<thead align="center" class="tHead">
<tr class="tr">
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr class="tr" v-for="(item,index) in book" key="index">
<th>{{index}}</th>
<th>《{{item.name}}》</th>
<th>{{item.date}}</th>
<th>¥{{item.price}}</th>
<th>
<button @click="numReduction(index)">-1</button>
{{item.num}}
<button @click="numAdd(index)">+1</button>
</th>
<th>
<button @click="deleteBook(index)">移除</button>
</th>
</tr>
</thead>
</table>
</div>
<span>
总价:
<label>¥{{TotalPrice}}</label>
</span>
</template>
<script src="https://unpkg.com/vue@next"></script>
<script>
const App = {
template: "#my-app",
data() {
return {
TotalPrice: 0,
input1: " ",
input2: " ",
input3: " ",
book: [
{
name: "算法导论",
date: "2006-9",
price: 85,
num: 1,
},
{
name: "UNIX编程技术",
date: "2006-2",
price: 59,
num: 1,
},
{
name: "编程珠玑",
date: "2008-10",
price: 39,
num: 1,
},
{
name: "代码大全",
date: "2006-3",
price: 128,
num: 1,
},
],
};
},
watch: {
book: {
handler(newBook, oldBook) {
let Price = 0;
newBook.forEach((item, index) => {
Price += item.price * item.num;
});
this.TotalPrice = Price;
},
deep: true,
immediate: true,
},
},
methods: {
addBook() {
if (
this.input1 != " " &&
this.input2 != " " &&
this.input3 != " "
) {
this.book.push({
name: this.input1,
date: this.input2,
price: this.input3,
num: 1,
});
}
this.input1 = " ";
this.input2 = " ";
this.input3 = " ";
},
deleteBook(index) {
this.book.splice(index, 1);
},
numAdd(index) {
this.book[index].num++;
},
numReduction(index) {
if (this.book[index].num > 0) {
this.book[index].num--;
}
},
},
};
Vue.createApp(App).mount("#app");
</script>
</body>
</html>