计算函数中未定义数据变量



我正在尝试使用API端点的照片为灯箱加载图像src。this.photos存储了我所有的对象,但我正在寻找变成"this.photos[x].photos"的url。

在库中,我试图将${this.photos[x].photos加载为src属性的字符串,但我一直收到一个错误:;照片未定义";

我测试了照片对象不是空的;http://localhost:8000/media/uploads/1_082720_soylent_PDPwebsite_PowderPouchCacao_1468x1100_A01-PouchShot_2048x2048.jpg";对于一个对象。

有时,如果我刷新页面,{{photos[2].photos}}也是未定义的,但{{photos}}不是,也许我应该使用不同于挂载的生命周期挂钩来获取照片?

谢谢!

存储在this.photos中的许多照片对象之一。为了只获取图像src,我将此示例称为this.photos[2].photos

{
"id": 3,
"photos": "http://localhost:8000/media/uploads/1_082720_soylent_PDPwebsite_PowderPouchCacao_1468x1100_A01-PouchShot_2048x2048.jpg",
"user": null
},
<template>
<div id="app">
<CoolLightBox :items="gallery" :index="index" @close="index = null">
</CoolLightBox>
<div class="images-wrapper">
<div
class="image"
v-for="(image, imageIndex) in items"
:key="imageIndex"
@click="index = imageIndex"
:style="{ backgroundImage: 'url(' + image + ')' }"
></div>
</div>
{{ photos[2].photos }}
</div>
</template>
<script>
import CoolLightBox from "vue-cool-lightbox";
import "vue-cool-lightbox/dist/vue-cool-lightbox.min.css";
export default {
name: "app",
data: function() {
return {
photos: [],
index: null
};
},
computed: {
galleryPhoto: function() {
return {
gallery: [
{
src: `${this.photos[2].photos}`
}
]
};
}
},
components: {
CoolLightBox
},
mounted() {
this.fetchPhotos();
},
methods: {
setIndex(index) {
this.index = index;
},
fetchPhotos($axios) {
this.$axios
.get("/api/v1/photos/")
.then(response => {
// console.log(response, "response");
this.photos = response.data;
})
.catch(error => {
console.log(error);
});
}
}
};
</script>

如果没有更多数据,很难理解您的问题。"{{照片}"中有多少个项目?例如。你说";。。。{photos[2].photos}}也未定义,但{{photos}}不是">这应该意味着{{photos}}包含的项目少于3个,或者{}的第3个元素是未定义的。

=>能否请您向我们提供{{照片}}的内容?

此外,我猜您的代码中还有另一个错误:在你的模板中你有

<CoolLightBox :items="gallery" :index="index" @close="index = null">
</CoolLightBox>

但是gallery并没有在你的scrip部分中定义,相反,你定义了galleryPhoto,它返回一个具有gallery属性的对象:

galleryPhoto: function() {
return {
gallery: [
{
src: `${this.photos[2].photos}`
}
]
};
}

=>因此,您可以修改模板以参考galleryPhoto.gallery:

<CoolLightBox :items="galleryPhoto.gallery" :index="index" @close="index = null">
</CoolLightBox>

或者更好的解决方案是修改计算的属性:

computed: {
gallery() {
return [
{
src: this.photos[2].photos
}
];
}
},

或者,如果你想显示所有照片:

computed: {
gallery() {
return !Array.isArray(this.photos) ? [] : this.photos.map(el => el?.photos);
}
},

最新更新