代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>vue学习</title>
<script src="./js/vue.js"></script>
<style>
li {
list-style-type: none;
}
</style>
</head>
<body>
<div id="app">
<input type="checkbox" v-model="all" />全选
<hr />
<ul>
<li v-for="item in carts" :key="item.id">
<span>
<input type="checkbox" :value="item.id" v-model="selectedUser" />
</span>
<span>商品名称:{{item.name}}</span>
<span>
<button @click="addNum(item,-1)">---</button>
商品数量:{{item.num}}
<button @click="addNum(item,1)">+++</button>
</span>
<span>商品单价:{{item.price}}</span>
</li>
</ul>
<hr>
<h3>合计:{{total}}</h3>
</div>
<script>
new Vue({
el: '#app',
data: {
all: false,
selectedUser: [],
carts: [
{ id: 1, name: 'aaa', price: 1, num: 1 },
{ id: 2, name: 'bbb', price: 1, num: 2 },
{ id: 3, name: 'ccc', price: 1, num: 3 }
],
title: ''
},
methods: {
addNum(item, num) {
item.num += num
if (item.num <= 1) item.num = 1
if (item.num >= 3) item.num = 3
}
},
computed: {
total() {
let selectedCarts = this.carts.filter(item => this.selectedUser.includes(item.id))
return selectedCarts.reduce((prev, { price, num }) => {
prev += price * num
return prev
}, 0)
}
},
watch: {
all(value) {
if (value) {
this.selectedUser = this.carts.map(item => item.id)
} else {
this.selectedUser =
this.selectedUser.length === this.carts.length ? [] : this.selectedUser
}
},
selectedUser(value) {
this.all = value.length === this.carts.length
}
}
})
</script>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。