使用vue3实现简单的书籍购物车
需求效果如图:
使用的软件为vscode
第一步:创建book.html文件
在文件上输入html5,并按Tab/回车,就会自动生成html5的模板
<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>书籍购物车</title>
</head>
<body>
</body>
</html>
第二步:编写界面样式
明显能看出这是一个表格,表格里面第一行是表头,下面还有四行数据
于是使用
标签,表头写在标签中,数据写在标签因为数据不可能只有一条,所以提前用变量来占位
点击按钮也顺便绑定上见名之意的事件
decrement(index),传入下标index,表示减少当前下标的count的数值
increment(index),传入下标index,表示增加当前下标的count的数值
del(index),传入下标index,表示删除当前下标的列/数据
@click:v-on:click的简写形式,绑定点击事件
:disabled:v-bind:disabled的简写形式,vue3专属,满足条件的时候禁用标签
<body>
<div id="app" style="width:90%;margin:auto;">
<table border="1" width="500px">
<thead>
<tr>
<td></td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<!-- 使用v-for从bookList里面获取书籍信息 -->
<tr v-for="(book,index) in bookList" :key="index">
<td>{{index+1}}</td>
<td>{{book.bname}}</td>
<td>{{book.publish}}</td>
<td>¥{{book.price}}</td>
<td>
<!-- :disabled是v-bind:disabled的简写 -->
<button @click="decrement(index)" :disabled="book.count == 1">-</button>
{{book.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="del(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价:¥{{sum}}</h2>
</div>
</body>
第三步:编写vue语句
书籍信息保存在bookList中
使用计算属性computed来计算价格总和,遍历bookList的书籍价格和数量,相乘并求和。计算属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算
减号点击事件,只有在数量大于1的时候才可以减少数量,每次点击count减1
加号点击事件,每次点击count加1
删除按钮点击事件,调用splice方法,传入两个参数,第一个参数是删除对象的下标,第二个参数是从这个坐标开始删除的个数,删除当前就是当前坐标,数量1
<!-- 导入vue.global.js -->
<script type="text/javascript" src="js/vue.global.js"></script>
<script>
// 1.创建app
const app = Vue.createApp({
// data: option api
data: function () {
return {
bookList: [
{ bname: '算法导论1', publish: '2006-1', price: 20, count: 1 },
{ bname: '算法导论2', publish: '2007-2', price: 40, count: 1 },
{ bname: '算法导论3', publish: '2008-3', price: 60, count: 1 },
{ bname: '算法导论4', publish: '2009-4', price: 80, count: 1 },
],
}
},
computed: {
// computed:计算属性
// 特点:计算属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算
sum() {
let sum = 0;
// forEach方法遍历
this.bookList.forEach(book => {
sum += book.price * book.count
});
return sum;
}
},
methods: {
// 减号点击事件,只有在数量大于1的时候才可以减少数量,每次点击count减1
decrement(i) {
if (this.bookList[i].count > 1) {
this.bookList[i].count--
}
},
// 加号点击事件,每次点击count加1
increment(i) {
this.bookList[i].count++
},
// 删除按钮点击事件,调用splice方法,传入两个参数
// 第一个参数是删除对象的下标,第二个参数是从这个坐标开始删除的个数
// 删除当前就是当前坐标,数量1
del(i) {
this.bookList.splice(i, 1)
}
}
})
// 2.挂载app
app.mount("#app")
</script>
最终效果展示
del(i) {
this.bookList.splice(i, 1)
}
}
})
// 2.挂载app
app.mount("#app")
```