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

后端 未结 5 797
礼貌的吻别
礼貌的吻别 2021-02-06 06:33

I\'d like to group some of my Vue.js methods together in a sort of \"submethod\" class, but I only seem to be able to have single level methods.

For example, if I wanted

5条回答
  •  佛祖请我去吃肉
    2021-02-06 07:09

    I use this pattern:

    Template:

    
    

    Script:

    ...
    methods: {
      test () {
        this.info('open')('test');
      },
      info (arg) {
        console.table({omg: [arg, '!']});
      },
      example (arg) {
        let self = this;
        const methods = {
          open (arg) {self.info(arg);},
          close (arg) { return self.example('play')(arg)},
          play (arg) {console.log(self, this)},
          stop () {console.error('Lo1')},
        };
        if (!Object.keys(methods).includes(arg)) return () => false;
        return methods[arg];
      },
    }
    ...
    

    And second case:

    Script:

    const fabric = (arg, foo, context) => {
      const methods = foo(context);
      if (!Object.keys(methods).includes(arg)) return () => false;
      return methods[arg];
    };
    
    export default {
      ...
      methods: {
        test () {
          this.info('open')('test');
        },
        info (arg) {
          console.table({omg: [arg, '!']});
        },
        example (arg) {
          return fabric(arg, (cnx)=>({
            open (arg) {cnx.info(arg);},
            close (arg) { return cnx.example('play')(arg)},
            play (arg) {console.log(cnx, this)},
            stop () {console.error('Lo1')},
          }), this);
        },
      }
      ...
    }
    

    Also, I think this is not a good practice, but it works and makes my work easier.

提交回复
热议问题