我有一种为俱乐部徽标图像构建URL的方法,如果该图像不存在,则为联赛徽标图像构建URL(这不是理想的方法,需要对其进行重构,但是它现在可以使用):
getLogoUrl: function(club, league) {
let imageExists = require('image-exists');
// First check if club logo exists
let src = "/images/logos/" + club + ".png";
console.log("FIRST "+src);
imageExists(src, function(exists) {
// Then get league logo
if (!exists) {
src = "/images/leagues/" + league + ".png";
console.log("SECOND "+src);
}
});
console.log("THIRD "+src);
return src;
}
第一次加载页面时(它通过mounted
中的API使用axios加载数据),它显示图像损坏。这是因为src
充满了俱乐部名称图像,该图像不存在。然后,当我单击页面上的链接,然后单击链接返回此页面时,它将正确显示联赛图像。
这是加载初始页面时的控制台输出(它加载了不存在的特定图像):
FIRST /images/logos/maidenhead-united.png
THIRD /images/logos/maidenhead-united.png
SECOND /images/leagues/the-conference.png
并且通过单击链接加载页面时(显示正确的图像):
FIRST /images/logos/maidenhead-united.png
SECOND /images/leagues/the-conference.png
THIRD /images/leagues/the-conference.png
那为什么在初始页面加载时未加载默认图像,但是在单击链接时加载了默认图像?可能是数据尚未完成加载,但是方法已经执行了吗?这是该组件中的所有代码:
<template>
<div class="visits row">
<div class="col-sm-3 visit" v-for="visit in visits" :key="visit.nr">
<div class="card">
<div class="card-header">{{ visit.nr }}</div>
<div class="card-body">
<router-link :to="{ name : 'VisitDetails', params: {id: visit.id}}">
<h5 class="card-title">{{ visit.home }}</h5>
</router-link>
<div class="logo">
<img :src="getLogoUrl(visit.home, visit.league)" class="card-img-center img-responsive center-block">
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'home',
data () {
return {
feedback: null,
visits: [],
errors: []
}
},
methods: {
getLogoUrl: function(club, league) {
let imageExists = require('image-exists');
// First check if club logo exists
let src = "/images/logos/" + club + ".png";
console.log("FIRST "+src);
imageExists(src, function(exists) {
// Then get league logo
if (!exists) {
src = "/images/leagues/" + league + ".png";
console.log("SECOND "+src);
}
});
console.log("THIRD "+src);
return src;
}
},
mounted() {
axios
.get(this.$baseURL + "/footmarks")
.then(response => {
console.log(response.data)
this.visits = response.data
})
.catch(e => {
console.log(this.errors)
})
}
}
</script>
<style scoped>
</style>
答案 0 :(得分:0)
看来,imageExists正在使用异步代码,并在异步检查图像是否首次存在之后(在代码中的THIRD之后发生),但是在第二次加载图像时,已经在回调中返回值。具有该值,因此SECOND会立即被调用并在THIRD之前发生。
您可以做的一件事是在回调中设置默认值:
let src = '/images/some-loading-image.png';
console.log("FIRST "+src);
imageExists(src, function(exists) {
// Then get league logo
if (!exists) {
src = "/images/leagues/" + league + ".png";
console.log("SECOND "+src);
} else {
src = "/images/logos/" + club + ".png";
}
});