vue

Grouping Related Methods Together in an Object in Vue

dexygen

George Jempty

Posted on January 7, 2020

Grouping Related Methods Together in an Object in Vue

tl;dr: https://stackoverflow.com/a/59614452/34806

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: https://stackoverflow.com/q/21285627/34806

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: https://dev.to/dexygen/linus-borg-s-nor-other-expert-s-advice-not-to-be-followed-blindly-1712)

There are a number of attempts at solving this given at: https://stackoverflow.com/questions/36108953/is-it-possible-to-nest-methods-in-vue-js-in-order-to-group-related-methods/ 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)}
  }
  this.on.test();
}

See this codepen https://codepen.io/dexygen/pen/povpxqy and open developer tools to see what gets logged.

💖 💪 🙅 🚩
dexygen
George Jempty

Posted on January 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related