购物车的简单功能vue实列实现单选多选

用vue实列来实现购物车的单选多选功能,使用了v-for v- model 使用@change来代替了@click

我们要知道怎么实现这个需求具体要怎么实现呢?

                点击每一个单选的情况,就判断arr和list的长度,

                如果相等就说明全部选中了,就要把全选框勾上

                如果不相等就要把全选框 取消勾选

话不多说代码如下:

这是页面的代码:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>
<body>

<div id="app">
	<table border="1">
		<thead>
			<tr>
				<th>
					<input type="checkbox" v-model="allFlag" @change="checkall">
				</th>
				
				<th>id</th>
				<th>商品名称</th>
				<th>商品价格</th>
				<th>商品数量</th>
				<th>小计</th>
			</tr>
		</thead>
		<tbody>
			{{arr}}
			<tr v-for="(item,index) in list" :key="item.id">

				<td> <input type="checkbox" :value="item.id" v-model="arr" @change="single"> </td>
				<td>{{item.id}}</td>
				<td>{{item.name}}</td>
				<td>{{item.price}}</td>
				<td>
					<button :disabled="item.num<=1" @click="sub(item)">-</button>	
					{{item.num}}
					<button @click="add(item)">+</button>
					<button @click="del(index)">x</button>
				</td>
				<td>{{item.num*item.price}}</td>
			</tr>

		</tbody>
	</table>
</div>
<script type="text/javascript" src="../lib/node_modules/vue/dist/vue.js"></script>
	<script type="text/javascript">
		const app = new Vue({
			el: '#app',
			data: {
				msg: 'test',
				allFlag: false,  // 记录全选框的状态
				arr: [], // 记录每一个单选的状态
				list: [
					{
						id: '001',
						name: 'HUAWEI',
						price: 200,
						num: 1
					},
					{
						id: '002',
						name: 'XIAOMI',
						price: 100,
						num: 3
					}
				]
			},
			methods: {
				add(product) {
					product.num++
					// console.log(product)
					// console.log('aaaaaaaaaaa')
				},
				sub(product) {
					product.num--
				},
				del(idx) {
					const flag = confirm('确定删除吗?')
					if (flag) {
						this.list.splice(idx, 1)
					}
					// alert('12')
					// console.log(idx)
					// this.list.splice(idx,1)
				},
				checkall() {
					// console.log(this.allFlag)
					if (this.allFlag) { // 全选选中的情况
						for (let i = 0; i < this.list.length; i++) {
							this.arr.push(this.list[i].id)
						}
					} else {
						this.arr = []
					}
				},
				single() {
					// 点击每一个单选的情况,就判断arr和list的长度,
					// 如果相等就说明全部选中了,就要把全选框勾上
					// 如果不相等就要把全选框 取消勾选

					// if(this.arr.length === this.list.length){
					// 	this.allFlag = true
					// }else{
					// 	this.allFlag = false
					// }

					this.allFlag = this.arr.length === this.list.length
				}
			}
		})
	</script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值