Vue之书籍购物车案例
2023-06-13 09:11:19 时间
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</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)" v-bind:disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格: {{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
<script>
</script>
</body>
</html>
main.js
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
]
},
methods: {
// getFinalPrice(price) {
// return '¥' + price.toFixed(2)
// }
increment(index) {
this.books[index].count++
},
decrement(index) {
this.books[index].count--
},
removeHandle(index) {
this.books.splice(index, 1)
}
},
computed: {
totalPrice() {
let totalPrice = 0
for (let i = 0; i < this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count
}
return totalPrice
// for (let i in/of this.books)
// reduce
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
style.css
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;
}
运行结果:
点击+ 直接计算出总价格:
点击移除按钮:
如果全部移除显示购物车为空:
相关文章
- vue 加载页面时触发时间_Vue 刷新页面时会触发事件吗「建议收藏」
- vue中新增属性视图问题
- Vue(3)webstorm代码格式规范设置与vue模板配置
- vue中通过路由跳转的三种方式
- vue.js 渲染函数_Vue.js的不可渲染且可扩展的RTF编辑器[通俗易懂]
- vue todolist案例_nodejs mvc
- vue面试常见考察点总结
- VUE请求跨域,如何设置代理
- Vue 2x 中使用 render 和 jsx 的最佳实践 (2)
- 合格vue开发者应该知道的面试题
- js 长轮询_websocket挂载到vue上
- vue改写数组方法_vue数组添加和删除
- Vue 快速体验
- VUE组件封装_vue组件内部双向绑定
- 新一代的vue状态管理插件Pinia
- Vue非父子组件传值之事件总线(eventbus)的使用方式
- vue源码分析-从new Vue开始_2023-02-24
- 基于Vue+SSM+SpringCloudAlibaba员工列表增删改查
- Vue提示框组件vue-notification使用实例演示
- 深入实战探究 Vue 2.7 Composition API 的强大之处
- Django+Vue前后端分离项目的部署详解编程语言
- 使用Vue技术从MSSQL中获取数据(vue获取mssql数据)
- Vue用Redis储存获取数据(vue获取redis)
- 用Vue从Redis中获取强有力的数据(vue用redis中数据)
- 构建基于Vue与Redis的高性能缓存系统(VUE redis缓存)