vuex表单处理_简单的Vuex模块可处理表单字段和验证

本文介绍了一个简单的Vuex模块,该模块用于处理表单字段和验证。你可以通过提供初始字段和验证器来构建模块,并将其映射到组件,以便轻松地进行表单验证。
摘要由CSDN通过智能技术生成

vuex表单处理

vuex模块有效状态 (vuex-module-validatable-state)

Simple Vuex module to handle form fields and validations.

简单的Vuex模块可处理表单字段和验证。

vuex-module-validatable-state

You can build a view model for your form, which runs valdations easily. You just provide initial fields and validators to build the module, then map getters/actions to components.

您可以为表单构建视图模型,从而轻松运行评估。 您只需要提供初始字段和验证器即可构建模块,然后将获取器/操作映射到组件。

用法 (Usage)

安装 (Installation)

$ npm i vuex-module-validatable-state

注册到核心Vuex模块 (Register to core Vuex module)

This module provides the function to return Vuex module as default. The function takes arguments:

该模块提供了默认返回Vuex模块的功能。 该函数接受参数:

  • Initial field set

    初始字段集

  • Validators

    验证者

A. Define directly A.直接定义
import validatableModule from "vuex-module-validatable-state";

const initialFields = {
  amount: null,
  description: "default text"
};

const validators = {
  amount: [
    ({ amount }) => amount === null ? "Require this" : false
  ],
  description: [
    ({ description }) => description.length > 15 ? "Should be shorter than 15" : false,
    ({ description, amount }) => description.indexOf(amount.toString())  ? "Should include amount" : false,
  ]
};

new Vuex.Store({
  modules: {
    myForm: {
      namespaced: true
      store,
      getters,
      actions,
      mutations,
      modules: {
        ...validatableModule(initialFields, validators) // <-- HERE
      }
    }
  }
});
B. Register to existing module B.注册到现有模块
import { register } from "vuex-module-validatable-state";

const initialFields = {
  amount: null,
  description: "default text"
};

const validators = {
  amount: [
    ({ amount }) => amount === null ? "Require this" : false
  ],
  description: [
    ({ description }) => description.length > 15 ? "Should be shorter than 15" : false,
    ({ description, amount }) => description.indexOf(amount.toString())  ? "Should include amount" : false,
  ]
};

const store = new Vuex.Store({
  modules: {
    myForm: {
      namespaced: true
      store,
      getters,
      actions,
      mutations
    }
  }
});

register(store, "myForm", initialFields, validators);

映射到组件 (Map to Components)

提供的吸气剂 (Provided Getters)
Getter nameReturns
GetterTypes.ALL_FIELDS_VALIDboolean whether all fields don't have error
GetterTypes.FIELD_VALUESAll fields as { [fieldName]: value }
GetterTypes.FIELD_ERRORSAll errors as { [fieldName]: errorMessage }
GetterTypes.FIELD_EDITABILITIESAll editable flags as { [fieldName]: editability }
GetterTypes.FIELD_DIRTINESSESAll dirtiness flags as { [fieldName]: dirtiness }
GetterTypes.ANY_FIELD_CHANGEDboolean whether all fields are not dirty
吸气剂名称 退货
GetterTypes.ALL_FIELDS_VALID boolean是否所有字段都没有错误
GetterTypes.FIELD_VALUES 所有字段均为{ [fieldName]: value }
GetterTypes.FIELD_ERRORS 所有错误均为{ [fieldName]: errorMessage }
GetterTypes.FIELD_EDITABILITIES 所有可编辑的标志为{ [fieldName]: editability }
GetterTypes.FIELD_DIRTINESSES 所有脏污标记为{ [fieldName]: dirtiness }
GetterTypes.ANY_FIELD_CHANGED boolean是否所有字段都不脏
提供的动作 (Provided Actions)

Import ActionTypes from the module.

从模块导入ActionTypes

Action nameRuns
ActionTypes.SET_FIELDSet value for a field, then runs validation if enabled
ActionTypes.SET_FIELDS_BULKSet values for fields at once, then make all dirtiness flags false
ActionTypes.RESET_FIELDSReset values on field with initial values
ActionTypes.ENABLE_ALL_VALIDATIONSEnable interactive validation and run validations for all fields
ActionTypes.VALIDATE_FIELD_VALUEValidate specific field
ActionTypes.VALIDATE_FIELDSValidate all fields
ActionTypes.SET_FIELDS_EDITABILITYSet editability flag for a field, disabled field is not updated nor validated
ActionTypes.SET_FIELDS_PRISTINEMake all dirtiness flags false
动作名称 运行
ActionTypes.SET_FIELD 设置字段的值,然后启用验证(如果启用)
ActionTypes.SET_FIELDS_BULK 一次设置字段的值,然后将所有脏污标志设为false
ActionTypes.RESET_FIELDS 用初始值重置字段上的值
ActionTypes.ENABLE_ALL_VALIDATIONS 启用交互式验证并运行所有字段的验证
ActionTypes.VALIDATE_FIELD_VALUE 验证特定字段
ActionTypes.VALIDATE_FIELDS 验证所有字段
ActionTypes.SET_FIELDS_EDITABILITY 设置字段的可编辑性标志,禁用的字段不会更新或验证
ActionTypes.SET_FIELDS_PRISTINE 将所有脏污标志设为假

验证者 (Validators)

You can pass validators when you initialize the module.

初始化模块时,可以通过验证器。

const validators = {
  amount: [/* validators for filling error against to amount */],
  description: [/* validators for filling error against to description */]
}

Each validator can take all fields values to run validation:

每个验证器都可以采用所有字段值来运行验证:

const validators = {
  amount: [
    ({ amount, description }) => /* return false or errorMessage */
  ]
}

Optionally, can take getters on the store which calls this module:

(可选)可以在调用此模块的商店上使用吸气剂:

const validators = {
  description: [
    ({ description }, getters) => getters.getterOnStore && validationLogicIfGetterOnStoreIsTruthy(description)
  ]
}

And you can request "interactive validation" which valites every time dispatch(ActionTypes.SET_FIELD) is called

并且您可以请求每次调用dispatch(ActionTypes.SET_FIELD)都有效的“交互式验证”

const validators = {
  amount: [
    [({ amount }, getters) => /* validator logic */, { instant: true }]
  ]
}

提供的打字 (Provided Typings)

You can import handy type/interface definitions from the module. The generic T in below expects fields type like:

您可以从模块中导入方便的类型/接口定义。 下面的通用T期望字段类型如下:

interface FieldValues {
  amount: number;
  description: string;
}

getters[GetterTypes.FIELD_VALUES] returns values with following FieldValues interface.

getters[GetterTypes.FIELD_VALUES]返回具有以下FieldValues接口的值。

<summary>See all typings</summary>

<summary>See all typings</summary>

ValidatorTree<T> (ValidatorTree<T>)

As like ActionTree, MutationTree, you can receive type guards for Validators. By giving your fields' type for Generics, validator can get more guards for each fields:

像ActionTree,MutationTree一样,您可以收到Validators的类型保护。 通过为泛型提供字段的类型,验证器可以为每个字段获得更多的防护:

image

SetFieldAction<T> (SetFieldAction<T>)

It's the type definition of the payload for dispatching ActionTypes.SET_FIELD, you can get type guard for your fields by giving Generics.

这是用于分配ActionTypes.SET_FIELD的有效负载的类型定义,您可以通过提供泛型来为字段获取类型保护。

image

FieldValidationErrors<T> (FieldValidationErrors<T>)

Type for getters[GetterTypes.FIELD_ERRORS]

getters[GetterTypes.FIELD_ERRORS]类型getters[GetterTypes.FIELD_ERRORS]

FieldEditabilities<T> (FieldEditabilities<T>)

Type for getters[GetterTypes.FIELD_EDITABILITIES]

getters[GetterTypes.FIELD_EDITABILITIES]类型getters[GetterTypes.FIELD_EDITABILITIES]

FieldDirtinesses<T> (FieldDirtinesses<T>)

Type for getters[GetterTypes.FIELD_DIRTINESSES]

getters[GetterTypes.FIELD_DIRTINESSES]类型getters[GetterTypes.FIELD_DIRTINESSES]

工作样本 (Working Sample)

注册到Vuex商店 (Registering to Vuex Store)

const initialField = {
  amount: 0,
  description: null
};

const validators = {
  amount: [
    ({ amount }) => (!amount ? "Amount is required" : false),
    ({ amount }) => (amount <= 0 ? "Amount should be greater than 0" : false)
  ],
  description: [
    ({ amount, description }) =>
      amount > 1000 && !description
        ? "Description is required if amount is high"
        : false
  ]
};

const store = new Vuex.Store({
  modules: {
    ...theModule(initialField, validators)
  }
});

映射到组件 (Mapping to Component)

<template>
  <form>
    <div>
      <label for="amount">Amount (Required, Positive)</label>
      <input type="number" name="amount" v-model="amount">
      <span v-if="errors.amount">{{ errors.amount }}</span>
    </div>
    <div>
      <label for="description">Description (Required if amount is greater than 1000)</label>
      <textarea name="description" v-model="description"/>
      <span v-if="errors.description">{{ errors.description }}</span>
    </div>
    <button @click.prevent="submit">Validate and Submit</button>
  </form>
</template>

<script>
import { GetterTypes, ActionTypes } from "vuex-module-validatable-state";

export default {
  name: "App",
  computed: {
    amount: {
      get() {
        return this.$store.getters[GetterTypes.FIELD_VALUES].amount;
      },
      set(value) {
        this.$store.dispatch(ActionTypes.SET_FIELD_VALUE, {
          name: "amount",
          value
        });
      }
    },
    description: {
      get() {
        return this.$store.getters[GetterTypes.FIELD_VALUES].description;
      },
      set(value) {
        this.$store.dispatch(ActionTypes.SET_FIELD_VALUE, {
          name: "description",
          value
        });
      }
    },
    errors() {
      return this.$store.getters[GetterTypes.FIELD_ERRORS];
    }
  },
  methods: {
    submit() {
      this.$store.dispatch(ActionTypes.ENABLE_ALL_VALIDATIONS).then(() => {
        if (this.$store.getters[GetterTypes.ALL_FIELDS_VALID]) {
          alert("Form is valid, so now submitting!");
          this.$store.dispatch(ActionTypes.SET_FIELDS_PRISTINE);
        }
      });
    }
  }
};
</script>

翻译自: https://vuejsexamples.com/simple-vuex-module-to-handle-form-fields-and-validations/

vuex表单处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值