Although I have a functional solution for this issue, it feels messy and not the ideal way to handle it in Vue.
The challenge is fetching data from a backend related to a "Vendor" entity, which includes photos that need to be displayed on the page. The goal is to show one photo at a time and then rotate through them every 5 seconds by changing their opacity using setInterval.
I have a 'ref' for the images but cannot access it within '.then' because this.$refs
is not available in created()
. Furthermore, the "refs" are also unavailable in mounted()
due to the asynchronous fetch call in created()
.
Placing setInterval in update is not an option since it would create a new listener for each update attempt (yes, I tried that...).
My current approach involves updated()
setting this.photoCount
whenever there's an update. setInterval is implemented in created()
but remains inactive until this.photoCount
is no longer null.
<template>
<!-- Your template content here -->
</template>
<script>
export default {
data(){
return {
vendor: {},
banner: {
displayed: false,
type: "",
message: ""
},
displayedPhoto: 0,
photoCount: null
}
},
created(){
let token = localStorage.getItem("jwt");
let headers = {"Content-Type": "application/json"};
if(token !== null) headers["Authorization"] = `Bearer ${token}`;
// Fetch vendor data
fetch(`http://localhost:8000/vendor${document.location.pathname}`, {
method: "get",
headers: headers,
})
.then(r=>r.json())
.then((vendor)=>{
this.vendor = vendor;
})
.catch((err)=>{
console.error(err);
});
// Setting up photo rotation with setInterval
setInterval(()=>{
if(this.photoCount !== null){
if(this.displayedPhoto >= this.photoCount){
this.displayedPhoto = 0;
}else{
this.displayedPhoto++;
}
}
}, 5000);
},
updated(){
// Calculate photo count once refs are available
this.photoCount = this.$refs.vendorPhoto.length;
}
What could be a more efficient and "vue-like" approach to tackle this issue? While my current solution works, it seems suboptimal.