最近进行了vue的基础学习,拿之前JS时写的代码改了改,用Vue的方法写了出来,在这里与大家分享一下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="./js/jquery-3.7.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@3.2.31/dist/vue.global.js" type="text/javascript" charset="utf-8"></script>
</head>
<style>
*{
padding: 0;
margin: 0;
}
#app{
width: 300px;
margin: 15% auto;
}
table{
width: 300px;
border-spacing: 0;
border-top: 1px solid gray;
border-left: 1px solid gray;
}
th{
font-weight: bold;
}
td,th{
border-right: 1px solid gray;
border-bottom: 1px solid gray;
text-align: center;
}
.add,.minus{
width: 20px;
height: 20px;
}
input{
width: 100px;
}
</style>
<body>
<div id="app">
<table>
<thead>
<tr>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in arrs" :style="{backgroundColor: item.num != 0? color: ''}">
<td>{{item.name}}</td>
<td>¥{{item.price}}</td>
<td><button class="minus" v-show="item.num != 0" @click="minus(index)">-</button>{{item.num}}<button class="add" @click="add(index)">+</button></td>
<td><button @click="edit(index)">编辑</button><button @click="isDelete(index)">删除</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td>总价:¥{{computed()}}</td>
<td>总数量: {{allNum()}}</td>
<td></td>
</tr>
</tfoot>
</table>
<div><button v-show="addCheck" @click="addGoods">添加商品</button></div>
<div v-show="editCheck+1" style="display: flex;align-items: center;">
<button @click="isConfirm()">保存</button><button @click="quit()">取消</button>
<input type="text" v-model="obj.name"/>
<input type="number" v-model="obj.price"/>
</div>
</div>
<script>
Vue.createApp({
data() {
return {
arrs: [
{
name: "衣服",
price: 10,
num: 1
},{
name: "鞋子",
price: 20,
num: 0
},{
name: "帽子",
price: 15,
num: 2
},{
name: "裙子",
price: 50,
num: 4
}
],
color: "red",
editCheck: -1,
addCheck: true,
obj:{
name: '',
price: '',
num: 0
}
}
},
methods: {
isDelete(index){
this.arrs.splice(index,1)
},
computed(){
var total = 0;
for (let i = 0; i < this.arrs.length; i++) {
total += parseInt(this.arrs[i].num)*parseInt(this.arrs[i].price);
}
return total;
},
allNum(){
var allNum = 0;
for (let i = 0; i < this.arrs.length; i++) {
allNum += parseInt(this.arrs[i].num);
}
return allNum;
},
minus(index){
this.arrs[index].num--;
},
add(index){
this.arrs[index].num++;
},
edit(index){
this.obj = JSON.parse(JSON.stringify(this.arrs[index]));
this.addCheck = true;
this.editCheck = index;
},
addGoods(){
this.addCheck = false;
this.editCheck = -2;
this.obj = {
name: '',
price: '',
num: 0
};
},
isConfirm(){
if(!this.addCheck&&this.obj.name&&this.obj.price){
this.arrs.push(this.obj);
}else if(this.addCheck&&this.obj.name&&this.obj.price){
this.arrs.splice(this.editCheck,1,this.obj)
}
this.addCheck = true;
this.editCheck = -1;
this.obj = {
name: '',
price: '',
num: 0
};
},
quit(){
this.addCheck = true;
this.editCheck = -1;
}
},
}).mount('#app');
</script>
</body>
</html>
具备了基本的增删改信息功能
不得不感叹新技术的强大,在之前需要费力处理的信息在vue的帮助下游刃有余,看来还是需要更加努力的学习知识
希望能为你带来帮助~