context "this" does not return correct

Asked

Viewed 40 times

0

When giving a console.log(this), I wanted the console’s THIS to return Vue, not Validate’s This,

this.$ValidateUtil({
        el: this.$refs.cadMain,
        rules: {
          cep: {
            required: true,
            regex: /^\d{5}-\d{3}$/
          }
        },
        messages: {
          cep: {
            regex: "CEP inválido"
          }
        },
        submitHandler: function () {
          // AQUI!! -->>console.log(this);
          return false;
        }
      })
import Vue from 'vue'
import 'jquery-validation'
var LibsUtil = (function () {
    function LibsUtil() {
    }
    LibsUtil.ValidateUtil = function (options) {
      options = options || {}
      $(options.el).validate({
        rules: options.rules || {},
        messages: options.messages || {},
        submitHandler: function (form) {
          if (typeof options.submitHandler !== 'undefined') {
            options.submitHandler(this, form)
          }
          return false;
        }
      })
      Return Vue;
    };

    LibsUtil.install = function (Vue) {
        Vue.ValidateUtil = LibsUtil.ValidateUtil;

        if (!Vue.prototype.hasOwnProperty("$ValidateUtil")) {
          Vue.prototype.$ValidateUtil = LibsUtil.ValidateUtil;
      }


    };
    return LibsUtil;
}());
export { LibsUtil };
export default LibsUtil;
  • Got it! instead of calling it options.submitHandler(this, form), I call it that: options.submitHandler.call(Vue,this, form)! ^^

1 answer

1

It happens that there are moments in some functions that change the context of this, and so you can no longer access it, an example of this is the function setInterval, where within the execution of the function is changed the context, and with that you no longer have access to this of the instance, to resolve this you can do as follows:

todo(){  
    const self = this; //preserva instancia do this na variavel self    
    this.intervalid1 = setInterval(function(){
        self.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

thus within the setInterval it is possible to use the instance of Vue with the variable "self", you can use this same strategy for this validation lib

Browser other questions tagged

You are not signed in. Login or sign up in order to post.