我有一个vue 2项目,它有多个从firebase获取图像的组件。我没有重写相同的API调用来获取每个组件中的图像,而是尝试创建一个可以被多个组件重用的方法。我尝试使用mixins,但是由于某种原因,在api用图像响应填充它之前,返回值就返回了。
父组件:
import getImage from "@/mixins/getImage";
export default {
name: "Test",
mixins: [getImage],
//data and other functions
methods: {
getPicture(product) {
this.image = this.getImage(`products/${product.productId}.jpg`);
},
我的mixin getImage.js:
import firebase from "firebase/app";
export default {
methods: {
getImage(imagePath) {
this.loading += 1;
firebase
.storage()
.ref(imagePath)
.getDownloadURL()
.then(url => {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = event => {
event.preventDefault();
return URL.createObjectURL(xhr.response);
};
xhr.open("GET", url);
xhr.send();
})
.catch(() => {
return "/noImage.jpg";
})
.finally(() => {
this.loading -= 1;
});
}
}
}
上面将返回一个undefined,我也尝试基于这个答案Vue methods mixins返回promise本身,如下所示:
父组件:
import getImage from "@/mixins/getImage";
export default {
name: "Test",
mixins: [getImage],
//data and other functions
methods: {
getPicture(product) {
this.getImage(`frames/${product.productId}.jpg`).then((r)=> this.image=r);
},
js:
import firebase from "firebase/app";
export default {
methods: {
getImage(imagePath) {
this.loading += 1;
return firebase
.storage()
.ref(imagePath)
.getDownloadURL()
.then(url => {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = event => {
event.preventDefault();
return URL.createObjectURL(xhr.response);
};
xhr.open("GET", url);
xhr.send();
})
.catch(() => {
return "/noImage.jpg";
})
.finally(() => {
this.loading -= 1;
});
}
}
}
这里发生的事情也是未定义的,最后我也尝试过使用一个返回对象,如下所示:
父组件:
import getImage from "@/mixins/getImage";
export default {
name: "Test",
mixins: [getImage],
//data and other functions
methods: {
getPicture(product) {
this.image = this.getImage(`frames/${product.productId}.jpg`);
},
js:
import firebase from "firebase/app";
export default {
methods: {
getImage(imagePath) {
let image = null;
this.loading += 1;
firebase
.storage()
.ref(imagePath)
.getDownloadURL()
.then(url => {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = event => {
event.preventDefault();
image = URL.createObjectURL(xhr.response);
};
xhr.open("GET", url);
xhr.send();
})
.catch(() => {
image = "/noImage.jpg";
})
.finally(() => {
this.loading -= 1;
});
return image;
}
}
}
但这也返回了未定义的,我知道事实上API调用不是问题,因为如果我控制台记录firebase调用响应,它是正确的,它只是没有将返回的图像传递到调用方法和我导入了mixin的父方法。我真的卡住了,不知道我还可以尝试什么。
1条答案
按热度按时间pjngdqdw1#
解决方案是使用firebase storage getblob来代替,这样我们就可以避免整个xhr的问题。下面是我最后做的工作: