vue商品列表页面axios请求获取后端返回的json数据
1、先看看后端返回给我们的是什么内容
我在postman输入相应接口,我们可以看到后端返回给我们的是一个list数组,我们需要把list里边相应的内容放到我们的前端固定的位置。
2、再看看前端需要达到的效果
- 首先页面可以获得后端返回的json数据,前端把它放到相应的位置,这里我们很容易想到v-for循环。
- 然后在点击列表中的一条内容后,就可以获取到那条json对应的id,同时获得详情页面的内容
3、就以日结-互联网运营这个列表为例来看代码
- 这是list页面的代码,首先为el-row标签设置v-for循环,List就是我们从后端获取的数组,item就是里边的个体。通过axios我们请求后端的数组,同时把这个数组放到我们前端定义的List里,这样就可以直接用后端里边的内容了。
<template>
<div class="app">
<el-row :gutter="5" type="flex" v-for="item in List" :key='item.id' @click.native="routerJump(item.id)" >
<el-col :span="8" :offset="1">
<div class="grid-content bg-purple">
<img :src="item.imgUrl">
</div>
</el-col>
<el-col :span="14">
<div class="grid-content bg-purple-light">
<span class="title">{{item.title}}</span><br>
<span class="price">{{'¥'+item.price+'/日'}}
<span class="way">{{item.typeOne}}</span>
</span>
<br>
<!-- 公司名称和地址 -->
<div class="LOCAL">
<span class="company">
{{item.companyName}}
</span>
<span class="city">
<i class="el-icon-location-information"></i>
{{item.address}}
</span>
</div>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
props: ['typeone','typetwo'],
data () {
return {
List: []
}
},
methods: {
getList() {
this.$axios({
method: 'get',
url: '/demo/job/find',
headers: {
'Content-Type': "application/json;charset=UTF-8",
},
params: {
typeOne: this.typeone,
typeTwo: this.typetwo
}
})
.then(res=>{ //请求成功后执行函数
if(res.data.code === 0){
//定义从后端获取的joblist
var res = res.data.data
this.List = res
console.log("获取成功")
}else{
console.log("获取失败")
}
})
.catch(err=>{ //请求错误后执行函
console.log("请求错误")
})
},
routerJump (e) {
this.$router.push({
path: '/detail', query: { id: e } })
localStorage.setItem('jobId',e)
console.log(e)
}
},
mounted: function () {
this.getList()
},
}
</script>
<style lang="scss">
.el-row {
height: 100px;
background-color: white;
margin-bottom: 10px;
// index:1000;
&:last-child {
margin-bottom: 70px;
}
}
.el-col {
text-align: LEFT;
img{
border-radius: 10px;
}
.title {
padding-top: 5px;
font-family: 宋体;
font-size: 16px;
font-weight: bold;
text-overflow: ellipsis;
display: -webkit-box;
margin-bottom: -1px;
}
.price {
font-family: 微软雅黑;
font-size: 16px;
color:rgb(240, 63, 63);
font-weight: normal;
}
.way {
margin-left: 5px;
border-radius: 30px;
background-color:#409EFF;
opacity: 0.7;
font-size: 12px;
color: white;
padding: 2%;
}
.LOCAL {
// display: -webkit-box;
overflow:auto;
padding-top: 20px;
font-size: 13px;
color: black;
span{
// text-align: left;
padding-left: 2px;
float: none;
}
.city{
float: right;
color: gray;
width: 100px;
i{
color: #409EFF
}
}
}
.grid-content {
height: 100px;
}
}
</style>
- 至于页面的跳转我这里用了一个routerJump (e) 方法,e就是这个item的id,然后跳转到对应的path就ok啦。
至此,商品列表获取完毕。