代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue-products</title>
<style type="text/css">
table{
border: 1px solid springgreen;
width: 100%;
border-collapse: collapse;
}
table th,td{
border: 1px solid springgreen;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<h1>Vue.js之商品查询 {{checkItems}}</h1>
<fieldset>
<legend>商品搜索</legend>
名称:<input type="text" v-model="query.name" placeholder="请输入商品名称"/>
类型:<select v-model="query.spuId">
<option value="-1">请选择</option>
<option value="1">小米手机</option>
<option value="2">红米手机</option>
</select>
<button type="button" v-on:click="search">搜索</button>
</fieldset>
<fieldset>
<button type="button" v-on:click="dels">批量删除</button>
<button type="button">添加商品</button>
</fieldset>
<table id="tbl">
<thead>
<tr>
<th>
全选
<input type="checkbox" v-model="checked" name="all" id="all" @change="AllChecked"/>
</th>
<th>编号</th>
<th>名称</th>
<th>图片</th>
<th>价格</th>
<th>类型</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<!--创造一个模板-->
<tr v-for="(p,index) in products" :key="p.id">
<td>
<input type="checkbox" v-bind:value="p.id" v-model="checkItems"/>
</td>
<td>{{p.id}}</td>
<td>{{p.name}}</td>
<td>
<img style="width:150px;height:150px" :src="'http://123.57.7.108:81/'+p.image"/>
</td>
<td>
{{p.price}}$
</td>
<td>
<span v-if="p.spuId==1">
小米手机
</span>
<span v-if="p.spuId==2">
红米手机
</span>
<span v-if="p.spuId==3">
华为手机
</span>
<span v-if="p.spuId==2">
朵唯手机
</span>
</td>
<td>
<span @click="del(p.id)">删除</span>
</td>
</tr>
</tbody>
</table>
</div>
<script src="js/jquery-3.5.1.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
var vue=new Vue({
el:"#app",
data:{
products:[],
query:{
name:"",
spuId:"-1"
},
checkItems:[],
checked:true
},
created(){
this.init();
},
methods:{
init:function(){
var _this=this;
$.ajax({
type:"get",
dataType:"json",
url:"http://123.57.7.108:83/product.json",
cache:false,
success(data){
_this.products=data;
}
});
},
del:function(id){
if(confirm("亲,你确定要删除吗?")){
for(let i=0;i<this.products.length;i++){
if(this.products[i].id==id){
this.products.splice(i,1);
break;
}
}
}
},
search:function(){
alert("正在搜索商品:名称是"+this.query.name+",类型是"+this.query.spuId);
},
dels:function(){
alert("正在批量删除,参数已经在data中,用this.checkItems");
},
AllChecked:function(){
if(this.checked){
this.products.forEach(element => {
this.checkItems.push(element.id);
});
}else{
this.checkItems=[];
}
}
}
}
);
</script>
</body>
</html>