Is it possible to nest methods in Vue.js in order to group related methods? Is it possible to nest methods in Vue.js in order to group related methods? vue.js vue.js

Is it possible to nest methods in Vue.js in order to group related methods?


The closest I've got to doing this, is to declare the parent as a function, and return an object with a set of methods.

Example:

new Vue({  el: '#app',  data: {},  methods: {    buttonHandlers: function() {      var self = this; // so you can access the Vue instance below.      return {        handler1: function() {          dosomething;          self.doSomething();        },        handler2: function() {          dosomething;        },      },    }  }});

And you can call the methods like this:

<button @click="buttonHandlers().handler1()">Click Me</button>


There is actually a very simple technique: define your nested methods in the created hook:

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

NOTE: Two things, A) in this case you must use arrow function(s) and B) if this feels "hacky" to you, perhaps because of the cluttering of the created lifecycle hook, you can always delegate to a method, let's say this.namespaceMethods(), e.g.:

created() {  this.namespaceMethods();  // call namespaced methods  this.foo.bar();  this.foobar.baz();  // etc.},methods: {  this.namespaceMethods() {    this.foo = {      bar: () => {console.log("foobar")}    },    this.foobar = {      baz: () => {console.log("foobarbaz")}    }  },  // etc}


if i had that problem, i would use a click handler() to delegate request to other methods.eg:

new Vue({    el: '#app',    data: { },    methods: {        handler1: function() {             console.log("handler 1 called");        },        handler2: function() {            console.log("handler 2 called");        },        buttonHandler:function(callback){            callback();        }    }});

and use html as

<button v-on:click="buttonHandler(handler1)">Click Me</button><button v-on:click="buttonHandler(handler2)">Click Me</button>

The code is only for demo. In real life i will be passing a number or string argument in template and using switch case to determine handler.