Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

krs's avatar
Level 17

How to access vue data inside of event handler

Hi boys and girls!

I don't get it right now... I have a Vue component, where I have two images. The height of the second image should be the same as the height of the first image, so they can line up nicely. To get the height of the first one, I do

    const image = new Image();
    image.onload = function() {
        console.log("height", this.height);
    };
    image.src = this.fn_x200;

which gives consoles out the height of the element. BUT I have to save this value in a data prop of the component

    data: function() {
        return {
            logo_height: null,
        }
    },

So how to access this logo_heigh from inside the onload event handler? If I use the syntax above, the this refers to the image, which I need to get the height. But if I use image.onload = () => { // } syntax, the this refers to the Vue component, but I can't access the height any more.

Where is my error in thinking? Pls help me out!

cheers Stefan

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Hello Stefan!

You're on the right track with using arrow functions to maintain the this context of the Vue component inside the event handler. To access both the Vue instance's data and the image's properties, you can use a separate variable to reference the Vue instance's this inside the onload function. Here's how you can do it:

export default {
    data: function() {
        return {
            logo_height: null,
        }
    },
    mounted() {
        const vm = this; // Store the Vue instance's 'this' in a variable
        const image = new Image();
        image.onload = function() {
            // 'this' refers to the image here
            console.log("height", this.height);
            // 'vm' refers to the Vue instance
            vm.logo_height = this.height;
        };
        image.src = vm.fn_x200; // Assuming 'fn_x200' is a reactive data property or computed property
    }
}

In the mounted hook, we store the Vue instance's this in a variable called vm. Inside the onload function, this refers to the image, so we can access its height. We then set the logo_height property of the Vue instance using vm.logo_height = this.height.

This way, you can access both the Vue instance and the image properties where needed.

krs's avatar
Level 17

Damn.... I like AI, I don't like AI, I like AI, I like AI, I don't like AI, ... :-)

Please or to participate in this conversation.