简体   繁体   English

如何在VueJS方法中访问表单变量

[英]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. 我认为这里的问题是,.then内部的回调函数具有自己的作用域,因此其自身的“ this”与组件中的“ this”不同。 It belongs to a different scope. 它属于另一个范围。 You can preserve the component's scope by doing var self = this; 您可以通过执行var self = this;来保留组件的范围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. 您还可以使用箭头函数(result) => { your callback logic.. }来代替常规的函数,然后在其中使用“ this”,然后在其中使用“ this”表示组件的“ this”,因为箭头函数没有一个单独的内部范围。

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实例上下文中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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