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

走远了吗. 提交于 2019-12-04 14:26:43

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>

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.

I had the same issue (the need of a namespace) while writing a Vue mixin. This answer doesn't directly address your case, but it could give a clue.

This is how I defined the mixin.

export default {
   created () {
    // How to call the "nested" method
    this.dummy('init')

    // Pass arguments
    this.dummy('greet', {'name': 'John'})
   },

   // Namespaced methods
   methods: {
     dummy (name, conf) {
       // you can access reactive data via `that` reference,
       // from inside your functions
       const that = this

       return {
         'init': function (conf) {
            console.log('dummy plugin init OK')
         },
         'greet': function (conf) {
            console.log('hello, ' + conf['name'])
         }
       }[name](conf)
     }
   }
 }

PS: for an official solution, Evan You said no.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!