Vue: How about add some hooks to 'v-on' directive, such as 'before' and 'after'

Created on 16 Mar 2016  ·  3Comments  ·  Source: vuejs/vue

New feature request:
How about add some hooks to 'v-on' directive, such as 'before' and 'after'.

What I want to do:
I want to add a some validate before click event being triggered, and lots of button not to be validated before click.

How it works:
If I have the before hook, I need to run the 'before method' and only the method return true I will do the real event binding.

Most helpful comment

You can simply do it inside the handler. If you need to reuse the same logic, you can either make that a filter or just compose it inside JS:

function guard (handler) {
  return function (e) {
    if (...) {
      e.preventDefault()
    }
    return handler.call(this, e)
  }
}

methods: {
  onClick: guard(function (e) {
    // ...
  })
}

All 3 comments

How I handle this at the moment:

...
  methods: {
    someButtonClickHandler () {
      new Promise( (resolve, reject) => {
          // setup logic
      })
        .then( (result) => {
           // before logic,
        })
        .then( (result) => {
           // the handler
        })
        .catch( (err) => {
           // handle exceptions
        })
        .finally( () => {
          // cleanup ?
        })
    }  
  }
...

Might not be the right way, but that's how I'm dealing with your use case.

specifically:

import store from 'application/store';
import {storeAnswer} from 'application/store/actions';
import validate from 'validate.js';

export default {

  vuex: {
    storeAnswer
  },

  computed: {

    firstName: {
      get () { return store.state.Thing.firstName; },
      set (value) {
        validate.async(data, constraints)
          .then( () => {
             this.storeAnswer(value);
          });
          .catch((err)=>{
            // handle validation errors ?
          });
      }
    }

  }
};


You can simply do it inside the handler. If you need to reuse the same logic, you can either make that a filter or just compose it inside JS:

function guard (handler) {
  return function (e) {
    if (...) {
      e.preventDefault()
    }
    return handler.call(this, e)
  }
}

methods: {
  onClick: guard(function (e) {
    // ...
  })
}

@yyx990803 All right, I guess I get your point, THX a lot

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guan6 picture guan6  ·  3Comments

seemsindie picture seemsindie  ·  3Comments

paceband picture paceband  ·  3Comments

hiendv picture hiendv  ·  3Comments

franciscolourenco picture franciscolourenco  ·  3Comments