【问题标题】:How to access form variables in method of VueJS如何在 VueJS 的方法中访问表单变量
【发布时间】:2019-04-21 07:01:29
【问题描述】:

无法访问表单变量。我收集 this 应该允许我访问 data 但我一直在控制台中看到未定义。

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

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

试试这个:

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

我认为这里的问题是您在 .then 中的回调函数有自己的范围,因此它自己的“this”与组件中的“this”不同。它属于不同的范围。您可以通过在回调之外执行 var self = this; 来保留组件的范围。

您还可以在“then 回调”中使用箭头函数(result) => { your callback logic.. } 代替常规函数,然后内部的“this”将表示组件的“this”,因为箭头函数没有单独的内部范围。

像箭头函数一样:

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

【讨论】:

    【解决方案2】:

    你必须在 Promise 处设置一个粗箭头函数,因为你不再处于 vue 实例上下文中。

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      相关资源
      最近更新 更多