原因可能是后台取出排序好的数据存到数组中的数据 不一定是排序好的,会动态更换,所以要根据优先级来排序
<template>
<div>
<el-row v-for="r in row" :key="r" :type="rowType" :justify="justify" class="recommend-row">
<el-col :span="12" v-for="c in col" :key="c">
<RecommendItem v-if="c<=col/2" class="right" v-bind="sortitems[col*(r-1)+c-1]"></RecommendItem>
<RecommendItem v-else class="left" v-bind="sortitems[col*(r-1)+c-1]"></RecommendItem>
</el-col>
</el-row>
<el-row class="recommend-row" v-if="showMore">
<el-col>
<MoreRecommend :span="24"></MoreRecommend>
</el-col>
</el-row>
</div>
</template>
<script>
import RecommendItem from "@/components/index/RecommendItem";
import MoreRecommend from "@/components/index/MoreRecommend";
export default {
name: "RecommendSection",
components: {RecommendItem, MoreRecommend},
data: function () {
return {
maxCol: 24,
items: [],
}
},
computed: {
//调用了排序后的数组
sortitems: function () {
return sortBykey(this.items, 'no')
}
},
created() {
this.$nextTick(() => {
// 请求推荐图片的数据
this.openLoading();
this.$axios.get('relatedImage?typename=推荐')
.then(res => {
// 添加到用于展示的数据数组中
for (let tea of res.data) {
// 根据id,
if (this.count == 0 || this.items.length < this.count) {
this.$axios.get(`/tea/${tea.teaid}`)
.then(res => {
this.items.push({
src: tea.imgurl,
url: "" + tea.teaid,
name: res.data.teaname,
no: tea.no,
})
});
} else {
break;
}
}
})
});
}
}
//渲染的时候从后台取的数据会乱 ,所以对数组对象优先级进行的排序
function sortBykey(ary, key) {
return ary.sort(function (a, b) {
let x = a[key]
let y = b[key]
return ((x < y) ? -1 : (x > y) ? 1 : 0)
})
}
</script>
之前页面直接用的items 现在页面用的是sortitems 已经根据no字段排序好的数组对象 主要是下面这两个方法进行排序 //排序后的数组 sortitems: function () { return sortBykey(this.items, 'no') },
//渲染的时候从后台取的数据会乱 ,所以对数组对象优先级进行的排序 function sortBykey(ary, key) { return ary.sort(function (a, b) { let x = a[key] let y = b[key] return ((x < y) ? -1 : (x > y) ? 1 : 0) }) }