DEV Community

George Jempty
George Jempty

Posted on

Grouping Related Methods Together in an Object in Vue


When first working with AngularJS about 6 years ago I was a bit distrurbed by the the lack of organization allowed within $scope --- both attributes and methods could be added anywhere in any order. So I asked the following question on stackoverflow:

In reply I not only got validation for my design, but also informed of an important, if esoteric reason, for why my idea was a good one in a way I'd not even thought of. When I moved to Vue years later, this was one of the improvements that I recognized: data was in data and methods in methods

Sometimes though you might like to further organize your Vue methods. For instance, if all handlers could reside within an on object, then it would be a matter of looping over them to nullify them in a beforeDestroy/destroyed hook lifecycle method (but be careful as noted here:

There are a number of attempts at solving this given at: but IMO not of them is particularly clean. My idea is to not add this object containing methods, to methods, but rather, to declare them in the created hook:

created() {
  this.on = {
    test: () => {console.log(this)}

See this codepen and open developer tools to see what gets logged.

Top comments (0)