【问题标题】:Vuejs Axios, When adding error to vee validate, error not showing (I explain more)Vuejs Axios,向vee validate添加错误时,错误未显示(我解释更多)
【发布时间】:2018-12-28 17:34:56
【问题描述】:

在我的 Vue 项目中,我使用 Vee-Validate 和 Axios。

我有一个 API 调用来注册用户,当我的电子邮件已被使用时,它会引发错误。使用 axios 我捕获了该错误并希望显示错误消息。很简单吧。只是这样做:

this.loading = true;

this.$http.post('v1/auth/register', {
  first_name: this.first_name,
  last_name: this.last_name,
  email: this.email,
  phone: this.phone,
  password: this.password
}).then((response) => {
  this.registration_card = 2;
}).catch(error => {
  if (error.data.error.message === "email_already_exists") {
    let input = this.$refs['email'].$children[0];
    input.errors.add({
      field: 'email',
      msg: 'email already in use'
    });
    // So the error is added and will be showing
    // Now disable the loading icon
    this.loading = false;
  }
});

所以在 catch 中我添加了错误并禁用了按钮内的加载图标。这是按钮组件:

<template>
  <button type="button">
    <span v-if="!loading">{{label}}</span>
    <loading v-if="loading"/>
  </button>
</template>

<script>
  import loading from 'vue-loading-spinner/src/components/Circle'

  export default {
    name: 'jellow-button',
    props: [
      'label',
      'loading'
    ],
    components: {
      loading
    }
  }
</script>

但是现在错误消息没有显示,甚至没有添加到错误包中。在执行{{this.errors}} 时,数组为空。我已经解决了这个问题,但我仍然想知道为什么这不起作用以及为什么它适用于我的解决方案。

按钮组件中的解决方案

改变这个:

<loading v-if="loading"/>

到这里:

<loading v-show="loading"/>

现在{{this.errors}}确实有错误项并显示错误。

对于这个问题,这并不是一个丑陋的解决方法,所以我可以接受,但我仍然想知道为什么它不能与 v-if 一起显示加载图标。这个按钮和错误包有什么关系?

【问题讨论】:

  • 显示完整代码,可以粘贴到gist.github.com 上面代码不完整,不好理解你的实现如何

标签: javascript vue.js vuejs2 axios vee-validate


【解决方案1】:

v-show 切换 display:nonev-if 从 DOM 中删除元素。

当你运行以下代码时

let input = this.$refs['email'].$children[0];

如果您使用v-if$refs 将无法在 DOM 上找到电子邮件元素。

【讨论】:

  • 让输入 = this.$refs['email'].$children[0];指的是自定义输入。不是按钮。 v-if 发生在按钮中,而不是自定义输入中。
猜你喜欢
  • 2021-02-09
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2018-12-01
  • 2023-01-03
  • 2020-08-18
相关资源
最近更新 更多