简体   繁体   中英

How to access form variables in method of VueJS

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

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

您必须在promise处设置一个粗箭头功能,因为您不再在vue实例上下文中使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM