0

Im working on a car sales website and using vue-router.

I have an index page with a list of all cars for sale, and then when clicked they link to the single view of that specific vehicle.

I have a large 'header' image on the single view page and have it inside a container with a fixed height so that when the page loads there is not jumping in page height.

When going to this single view, I do an API call to get the vehicle data and then wish to fade in the heading image.

To do this:

 <div class="singleVehicle__mainImage">
     <span :style="styles" :class="{'imageLoaded' : mainImageLoaded }" v-if="vehicle"></span>
 </div>

 export default {
    data() {
        return {
            vehicle: null,
            styles: {
                backgroundImage: null
            },
            mainImageLoaded: null
        }
    },
    created() {
        this.getVehicle().then(() => {
            this.mainImageBackground();
        });
    },
    methods: {
        mainImageBackground() {
            var source = "IMAGE SOURCE URL";
            this.styles.backgroundImage = "url("+source+")";

            var $this = this;
            var img = new Image();
            img.onload = function() {
                $this.mainImageLoaded = true;
            }
            img.src = source;
            if (img.complete) img.onload();
        }
    }
}

By default, the span inside the image wrapper has a 0 opacity and then that is transitioned to 1 when the .imageLoaded class is added.

This works fine, but only the first time each vehicle loaded. The image waits till it loads and then fades in. Everyother time afterwards the image simply pops in when it loads almost like the imageLoaded class is not being reset / the data is not being reset when leaving the view.

When clearing browser cache, it works again but once for each vehicle view.

1 Answer 1

1

This is probably due to your v-if="vehicle". The vehicle call is possibly taking longer and so the span is not showing until after the class is added or some timing issue related to that.

Sign up to request clarification or add additional context in comments.

2 Comments

That seemed to do it, can't get my head around why currently but im sure I will.
It seems you have two concurrent calls that are independently controlling the visibility of that span. One is the vehicle data being loaded, the other is the image being loaded. By removing the v-if, the vehicle data may not be loaded but the image could be, allowing the image to fade in as soon as it loads. If you wanted to make it "full proof" I would load the vehicle data in, then load the background image when that finishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.