<!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>
<script src="https://unpkg.com/vue@3"></script>
</head>
<body>
<div id="app"></div>
<template id="root">
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>单价</th>
<th>金额</th>
<th>数量</th>
</tr>
<tr v-for="(item,key) in shop">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>价格:{{item.prices}}</td>
<td>{{item.number}}</td>
<td>
<button @click="jia(key)">+</button>
<button @click="jian(key)">-</button>
</td>
</tr>
</table>
</template>
<script>
Vue.createApp({
template:`#root`,
data() {
return {
shop:[
{id:1,name:'Java无难事',price:188,prices:188,number:1},
{id:2,name:'VC++深入详解',price:168,prices:168,number:1},
{id:3,name:'Serve/Jsp深入详解',price:139,prices:139,number:1}
],
}
},
methods: {
jia(key){
this.shop[key].number+=1;
this.shop[key].prices=this.shop[key].price*this.shop[key].number;
},
jian(key){
if(this.shop[key].number>0){
this.shop[key].number-=1;
this.shop[key].prices=this.shop[key].price*this.shop[key].number;
}
},
},
}).mount('#app')
</script>
</body>
</html>
key的传递极为重要,它将确定你的值是否能被获取
效果图: