【问题标题】:How to use Vuex state when creating custom validation with Vee Validate使用 Vee Validate 创建自定义验证时如何使用 Vuex 状态
【发布时间】:2018-08-01 18:17:24
【问题描述】:

我正在尝试执行以下操作:

我想像这样从 Vuex 商店传递一个令牌:

<template>
  ...
  <div class="col-md-12">
    <label for="email" class="label-input">E-mail address</label>
    <input v-validate="validations.user.email" v-model="data.user.email" id="email" class="form-control" type="email" name="email" placeholder="Enter e-mail" />
    <div v-show="errors.has('email')" id="email-error" class="msg-error text-danger">{{ errors.first('email') }}</div>
  </div>
  ...
</template>

<script>
  ...
  const isUnique = (value) => {
    debugger;
    return axios.post('/api/v1/users/email_validations', { email: value, token: this.$store.state.auth.JWT }).then((response) => {
      // Notice that we return an object containing both a valid property and a data property.
      return {
        valid: response.data.valid,
        data: {
          message: response.data.message
        }
      };
    });
  };

  // The messages getter may also accept a third parameter that includes the data we returned earlier.
  Validator.extend('unique_email', {
    validate: isUnique,
    getMessage: (field, params, data) => {
      return data.message;
    }
  });
  ...

  export default {
    ...
  }
</script>

我想创建一个向 API 发送请求的自定义验证。但是,我无法访问“导出默认值”部分之外的 this.$store。我没有定义。

然后,我想将此代码提取到文件中并导入需要它的组件中。我怎么能这样做?

我是 Vue.js 和 Vee 验证的新手,如果这是一个简单的问题,很抱歉。

感谢您的时间和关注。

【问题讨论】:

  • 您可以尝试在 &lt;script&gt; 部分中的代码之前导入商店。 import store from '@/store/index' 左右然后使用store.state 而不是this.$store.state,这至少在路由器文件中有效。
  • 当我尝试导入商店时。当我尝试访问它时出现此错误“未捕获的 ReferenceError:未定义存储”。在脚本部分,这是“Module {__esModule: true, Symbol(Symbol.toStringTag): "Module"}”。这对你来说意味着什么?

标签: vue.js vee-validate


【解决方案1】:

Vee-validate 不提供任何直接访问组件/实例属性的方法。因此,您无法在自定义验证器代码中访问 this.$store。有多种替代方法可以实现这一目标。

首先,您可以为令牌设置一个隐藏的只读输入字段,并将其用作验证您的唯一字段的目标。更多信息请查看documentation

此外,您可以尝试将令牌存储为 instance property,然后在您的验证器代码中使用它。

在 Vue 实例中:

mounted() {
    Vue.prototype.token = this.$store.state.auth.JWT;
}

然后在您的验证器文件中:

import Vue from "vue";
...
const isUnique = (value) => {
//other code
return axios.post('/api/v1/users/email_validations', { email: value, token: Vue.prototype.token }).then((response) => {

  return {
    valid: response.data.valid,
    data: {
      message: response.data.message
    }
  };
});

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2021-11-17
    • 2020-06-20
    • 2018-11-25
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2020-01-15
    • 2020-11-21
    相关资源
    最近更新 更多