计算总价是由total函数的返回值决定的,将过滤出来符合条件的赋值给data中的另一个变量,就会出现栈溢出,但是如果不声明newarr这个变量,就不会报错,希望得到解答
<!DOCTYPE html>
<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>Document</title>
</head>
<style>
.disable {
opacity: 0.5;
pointer-events: none;
}
</style>
<body>
<div id="app">
<table>
<tr v-for="(item,index) in itemlist" ::key="item.num">
<td><input type="checkbox" v-model="item.check"></td>
<td>
<button @click="nums(-1,index)">-</button>
{{item.num}}
<button @click=nums(1,index)>+</button>
</td>
</tr>
</table>
<div>总价{{total()}}</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
itemlist: [{
num: 1,
price: 10,
check: false,
}, {
num: 1,
price: 11,
check: false,
}, {
num: 1,
price: 121,
check: false,
}],
newarr: []//如果把他注释,就不会报错
},
methods: {
nums(a, index) {
this.itemlist[index].num += a
},
total() {
this.newarr = this.itemlist.filter(items => {
return items.check
})
let aa = 0
this.newarr.forEach(item => {
aa += item.price * item.num
})
return aa
}
},
})
</script>
</body>
</html>