是否可以在 Vue.js 中嵌套方法以对相关方法进行分组?

Geo*_*ggs 11 javascript methods nested namespaces vue.js

我想将我的一些 Vue.js 方法组合在一种“子方法”类中,但我似乎只能拥有单级方法。

例如,如果我想要一组纯粹处理按钮操作的方法:

new Vue({

    el: '#app',

    data: { },

    methods: {

        buttonHandlers: {

            handler1: function() {
                dosomething;
            },

            handler2: function() {
                dosomething;
            }

        }

    }

});
Run Code Online (Sandbox Code Playgroud)

我希望能够然后使用类似的东西:

<button v-on:click="buttonHandlers.handler1">Click Me</button>
Run Code Online (Sandbox Code Playgroud)

但什么也没有发生。

已经试过迫使功能加入括号运行:

<button v-on:click="buttonHandlers.handler1()">Click Me</button>
Run Code Online (Sandbox Code Playgroud)

但我收到此控制台错误:

未捕获的类型错误:scope.buttonHandlers.handler1 不是函数

我已经设置了一个小的https://jsfiddle.net/ozx9oc4c/来演示我的意思。

如果有人知道在 Vue.js 中对父方法下的函数进行逻辑分组的方法,而不是没有真正结构的单级方法的页面和页面,我会很感激你的知识。

Alb*_*ion 10

我要做的最接近的是将父级声明为一个函数,并返回一个具有一组方法的对象。

例子:

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;
        },

      },

    }

  }

});
Run Code Online (Sandbox Code Playgroud)

你可以像这样调用方法:

<button @click="buttonHandlers().handler1()">Click Me</button>
Run Code Online (Sandbox Code Playgroud)


Geo*_*pty 6

实际上有一个非常简单的技术:在created钩子中定义你的嵌套方法:

created() {
  this.on = {
    test: () => {console.log(this)}
  }
  this.on.test();
}
Run Code Online (Sandbox Code Playgroud)

注意:两件事,A)在这种情况下,您必须使用箭头函数和 B)如果这对您来说是“hacky”,也许是因为created生命周期钩子的混乱,您总是可以委托给一个方法,比方说this.namespaceMethods(),例如:

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
}
Run Code Online (Sandbox Code Playgroud)


Raj*_*mal -1

如果我遇到这个问题,我会使用单击处理程序()将请求委托给其他方法。例如:

new Vue({

    el: '#app',

    data: { },

    methods: {

        handler1: function() {
             console.log("handler 1 called");
        },

        handler2: function() {
            console.log("handler 2 called");
        },

        buttonHandler:function(callback){
            callback();
        }


    }

});
Run Code Online (Sandbox Code Playgroud)

并使用 html 作为

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

<button v-on:click="buttonHandler(handler2)">Click Me</button>
Run Code Online (Sandbox Code Playgroud)

该代码仅用于演示。在现实生活中,我将在模板中传递数字或字符串参数,并使用 switch case 来确定处理程序。

  • 不幸的是,这个解决方案仍然让我处于同样的位置,我最终在 _methods_ 对象的顶层有 3 个函数 - 层次结构中没有逻辑组织。 (3认同)