'How to have a Onload event with Vuejs - specifically how to put the script in the method and the way to get a call in the html

export default {

    methods: {
    hotbod() { document.querySelector("body")},

    doStuff() {
      hotbod.className += " animate";
    },


    window:onload = function() {
      doStuff();
    },
      },
    }

Above is the code, that I think has some errors in it - and for some reason I cannot get the javascript to work (On page load, there are CSS that gets loaded).



Solution 1:[1]

If you want to call a method upon the emission of the window onload event, simply use a relevant Vue lifecycle hook to attach the event listener. For example:

export default {
    create() {
        window.addEventListener("load", this.onWindowLoad);
    },
    methods: {
        onWindowLoad() {
            console.log("window load event");
        },
    },
};

Instead of created, you might also use beforeCreate, beforeMount, or mounted. I don't think there's functionally a difference in this case.

You also may want to detach the listener upon the component's destruction (hooks beforeDestroy and destroy), though in practice, because it's only firing once, it may not matter.

Also note that, for reasons of scope, if you use an anonymous callback function, it must be an arrow function.

Solution 2:[2]

To launch a component method on the window's load, simply add the load listener in your mounted() hook. For example:

mounted(){
    window.addEventListener("load", () => this.processLoad());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 benas
Solution 2 Michael Sinclair