1

Having trouble accessing form variables. I gather this should allow me access to the data but I keep seeing undefined in the console.

Vue.use(VeeValidate);

new Vue({
  el: "#app",
  data: {
    form: {
      duration: 7
    }
  },
  methods: {
      doSubmit() {
       this.$validator.validateAll().then(function(result){
        if (!result){
            //this means a validation failed, so exit without doing anything
            console.log('did not work')
            return;
        }
        console.log('did work, duration is:')
        console.log(this.form)
       });
      }
    }
});
1

2 Answers 2

2

Try this:

Vue.use(VeeValidate);

new Vue({
  el: "#app",
  data: {
    form: {
      duration: 7
    }
  },
  methods: {
      doSubmit() {
       var self = this;
       this.$validator.validateAll().then(function(result){
        if (!result){
            //this means a validation failed, so exit without doing anything
            console.log('did not work')
            return;
        }
        console.log('did work, duration is:')
        console.log(self.form)
       });
      }
    }
});

I think the issue here that your callback function inside .then has its own scope therefore its own 'this' is not the same as the 'this' in your component. It belongs to a different scope. You can preserve the component's scope by doing var self = this; outside your callback.

You can also use an arrow function (result) => { your callback logic.. } instead of your regular function in your 'then callback' and then 'this' inside will mean your component's 'this', since arrow functions does not have a separate internal scope.

like so with arrow function:

new Vue({
  el: "#app",
  data: {
    form: {
      duration: 7
    }
  },
  methods: {
      doSubmit() {
       this.$validator.validateAll().then((result) => {
        if (!result){
            //this means a validation failed, so exit without doing anything
            console.log('did not work')
            return;
        }
        console.log('did work, duration is:')
        console.log(this.form)
       });
      }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You have to fo a fat arrow function at the promise, because you are not anymore at the vue instance context.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.