当后台只返回一维数组前端展示需要遍历el-row按行按列展示的时候自定义封装的二维数组
程序员文章站
2022-05-26 23:52:33
...
methods中或者工具函数utils中定义chunk方法,调用并传入参数即可得到二维数组,参数是待处理的一维数组和每列展示多少个,我是每列展示4个数据
chunk(array, size) {
//获取数组的长度,如果你传入的不是数组,那么获取到的就是undefined
const length = array.length
//判断不是数组,或者size没有设置,size小于1,就返回空数组
if (!length || !size || size < 1) {
return []
}
//核心部分
let index = 0 //用来表示切割元素的范围start
let resIndex = 0 //用来递增表示输出数组的下标
//根据length和size算出输出数组的长度,并且创建它。
let result = new Array(Math.ceil(length / size))
//进行循环
while (index < length) {
//循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
result[resIndex++] = array.slice(index, (index += size))
}
//输出新数组
return result
},
后台返回的base64流数据前台得加图片前缀否则加载不出来;
将后台数据整理成需要的数组arr;调用chunk方法 let result= this.chunk(arr,4);4是每行4条数据展示;获得二维数组;
async getBooksList() {
const paramsobj = invalidProperty(this.requestParams)
let res = await getBookList(paramsobj)
const { list, total } = initRes(res)
let arr = list.map(item => {
let obj = {
SJID: item.SJID,
bookName: item.SJMC,
press: item.SJCBS,
author: item.SJZZ,
FILE_STREAM: `data:image/jpg;base64,${item.FILE_STREAM}`
}
return obj
})
let result= this.chunk(arr,4);
this.booksList = result;
this.homeTotal = Number(total)
},
前台el-row和el-colum的遍历代码;v-if和v-for不要同行使用,外面套一层er-row
<el-row v-if="booksList.length!=0">
<el-row :gutter="10" class="main-img" v-for="(op,index) in booksList" :key="index">
<el-col :span="6" v-for="item in op" :key="item.SJID">
<el-card :body-style="{ padding: '0px' }" @click.native="jumpToDetail(item)">
<div
style="display: flex;
align-items: center;
justify-content: center;"
>
<el-image
:lazy="true"
style="cursor:pointer;width:150px;height:150px"
:src="item.FILE_STREAM"
fit="fill"
>
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
<div style="padding: 12px;" class="book-title">
<h2>{{item.bookName}}</h2>
<div class="author">
<span>{{item.author}}</span>
<span>著</span>
</div>
<span>{{item.press}}出版社</span>
</div>
</el-card>
</el-col>
</el-row>
</el-row>
上一篇: 【linux】56、socket