天天看點

js之購物車代碼邏輯

<template>
	<div class="about">
		<div>
			<table style="width: 1000px;">
				<tr>
					<!-- <th><h1>購物車</h1></th> -->
				</tr>
				<tr>
					<th><input type="checkbox" @change="handleChange()" v-model="flag"></th>
					<th>序号</th>
					<th>名稱</th>
					<th>價格</th>
					<th>數量</th>
					<th>操作</th>
				</tr>
				<tr v-for="item in dataList">
					<td><input type="checkbox" v-model="checkgroup" :value="item" @change="handleChange1()"></td>
					<td>{{item.id}}</td>
					<td>{{item.name}}</td>
					<td>{{item.price}}</td>
					<td>
						<button @click="jian(item)">-</button>
						{{ item.number }}
						<button @click="item.number++">+</button>
					</td>
					<td>
						<button @click="tel">删除</button>
					</td>
				</tr>
			</table>
			checkgroup:{{ checkgroup }}
			<p>商品總價:{{ getsum() }} 元</p>
			<!-- <p>商品總價:{{ goodsTotalPrice }}</p> -->
		</div>
	</div>
</template>
<script type="text/javascript">
	export default {
		data() {
			return {
				checkgroup: [],
				flag: false,
				dataList: [{
						'id': 1,
						'name': '鉛筆',
						'price': 1,
						'number': 100
					},
					{
						'id': 2,
						'name': '文具盒',
						'price': 5,
						'number': 25
					},
					{
						'id': 3,
						'name': '乒乓球',
						'price': 10,
						'number': 30
					},
					{
						'id': 4,
						'name': '籃球',
						'price': 60,
						'number': 0
					},
					{
						'id': 5,
						'name': '固體膠',
						'price': 0.5,
						'number': 500
					},
					{
						'id': 6,
						'name': '漫畫',
						'price': 10.5,
						'number': 3
					},
				]
			}
		},
		methods: {
			// 全選全不選
			handleChange() {
				console.log('改變了', this.flag)
				if (this.flag) {
					this.checkgroup = this.dataList
				} else {
					this.checkgroup = []
				}
			},
			// 反選
			handleChange1() {
				console.log('handleChange1 判斷是不是都勾選或有一個未勾選')
				if (this.checkgroup.length === this.dataList.length) {
					this.flag = true
				} else {
					this.flag = false
				}
			},
			// 總價/*  */
			getsum() {
				var sum = 0
				for (var i in this.checkgroup) {
					sum += this.checkgroup[i].price * this.checkgroup[i].number
				}
				return sum
			},
			// 數量減
			jian(item) {
				console.log("減")
				var number = item.number--
				if (number === 1) {
					item.number = 1
				}
			},
			tel(t) {
				console.log("删除")
			}
		}
	}
</script>
           

繼續閱讀