首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用ajax调用异步和等待验证规则

如何使用ajax调用异步和等待验证规则
EN

Stack Overflow用户
提问于 2019-05-29 06:13:06
回答 2查看 3.8K关注 0票数 0

我正在使用Vuetify表单验证来检查输入字段,我想知道是否可以调用ajax get调用并让它等待,这样我就可以在规则中使用结果了。

我已经在下面尝试过了,但似乎不起作用!

export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },


      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }
EN

回答 2

Stack Overflow用户

发布于 2019-05-29 06:24:20

newLocationNameSearch是一个异步函数。异步函数返回promises,因此当您编写

var hasName = this.newLocationNameSearch(value);

hasName被设置为一个承诺,它总是真实的。

你需要这样的东西:

    isLocationNew: async value => {

      if (value == '' || value == null || value.length <= 1) {
        this.validLocation = false;
        return 'Invalid length.';
      }

      this.validLocation = true;

      var hasName = await this.newLocationNameSearch(value);
      if (hasName) {
        return 'Location name already exists.';
      } else {
        return true;
      }
    }

请记住,无论在哪里调用isLocationNew,都需要等待它。

此外,newLocationNameSearch方法在等待时实际上并不返回值。

      await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      }).then(response => {
        return response.data;
      }).catch(function(error) {
        console.log(error)
      })

.then()调用的回调中包含返回语句。然后,newLocationNameSearch不返回任何内容,这意味着它返回undefined,这是错误的。

好消息是,async/await意味着我们不必再为then回调而烦恼了。

我们可以改写

try {
     var response = await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      });

      return response.data;

} catch (error) {
    console.log(error)
}
票数 0
EN

Stack Overflow用户

发布于 2019-05-29 07:10:27

methods: {
  fetchUserData: async function() {
      const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
      );
      this.users = await response.json();
}

你可以像这个例子一样使用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56350690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档