Ant Design of Vue a-form表单效验用法(二)

vue

Ant Design of Vue a-form表单效验用法(二)

  (这里添加上期的间隔效验用法:v-if导致的表单不能效验问题,moment时间的用法,表单回调)

效果图:

1、(选中周期时在选中生效时段,失去焦点后效验:)

 2、

1、(首日、最后一日、几号 同)

2、

 (这里考虑到如果先选择生效时段在选周期的话,采用提交表单时效验)

HTML:

<template>

<div class="createRules">

<a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 15 }" @submit="handleSubmit">

<div v-show="showVaildTypeInterval">

<a-form-item label="间隔周期" v-show="intervalShow">

<a-radio-group @change="intervalPeriod" v-decorator="['ruleVaildIntervalTime.interval', { rules: [{ required: true, message: '请选择间隔周期!' }] }]">

<a-radio-button value="每日">每日</a-radio-button>

<a-radio-button value="每周">每周</a-radio-button>

<a-radio-button value="每月">每月</a-radio-button>

</a-radio-group>

</a-form-item>

<a-form-item label="选择周期" v-show="period">

<a-checkbox-group v-decorator="['ruleVaildIntervalTime.exWeekly', { rules: [{ required: weekRequired, message: '请选择周期!' }] }]">

<a-checkbox value="周一">周一</a-checkbox>

<a-checkbox value="周二">周二</a-checkbox>

<a-checkbox value="周三">周三</a-checkbox>

<a-checkbox value="周四">周四</a-checkbox>

<a-checkbox value="周五">周五</a-checkbox>

<a-checkbox value="周六">周六</a-checkbox>

<a-checkbox value="周日">周日</a-checkbox>

</a-checkbox-group>

</a-form-item>

<a-form-item label="选择周期" v-show="periodDate">

<a-radio-group @change="periodType" v-decorator="['ruleVaildIntervalTime.exMonthly1', { rules: [{ required: monthRequired, message: '请选择每月周期!' }] }]">

<a-radio value="首日">首日</a-radio>

<a-radio value="最后一日">最后一日</a-radio>

<a-radio value="几号"></a-radio>

</a-radio-group>

<a-input-number

:min="2"

:max="30"

style="width: 50px; margin-right: 8px"

placeholder="N"

:disabled="monthDisabled"

v-decorator="['ruleVaildIntervalTime.exMonthly2', { rules: [{ required: requiredDay, message: '请输入几号!' }] }]"/>

<label>日</label>

</a-form-item>

<a-row type="flex" align="top">

<a-col :span="6">

<a-form-item label="起止时间" v-if="endingTime" :labelCol="{span: 9}" :wrapper-col="{ span: 8 }">

<a-time-picker

:open.sync="open"

format="HH:mm"

placeholder="开始"

style="width: 80px"

@change="(val,dateStrings)=>changeTime(val,dateStrings,'startTime')"

v-decorator="['ruleVaildIntervalTime.exDateTimeOnt', { rules: [{ required: requiredIntervalTime, message: '请选择开始时间!' }] }]"

>

<a-button slot="addon" size="small" type="primary" @click="handleClose">确定</a-button>

</a-time-picker>

</a-form-item>

</a-col>

<a-col style="height: 40px;line-height: 40px;padding: 0 2px">~</a-col>

<a-col :span="10">

<a-form-item>

<a-time-picker

:open.sync="open2"

format="HH:mm"

placeholder="结束"

style="width: 80px"

:disabledHours="getDisabledHours"

:disabledMinutes="getDisabledMinutes"

@change="(val,dateStrings)=>changeTime(val,dateStrings,'endTime')"

v-decorator="['ruleVaildIntervalTime.exDateTimeTwo', { rules: [{ required: requiredIntervalTime, message: '请选择结束时间!' }] }]"

>

<a-button slot="addon" size="small" type="primary" @click="handleClose">确定</a-button>

</a-time-picker>

</a-form-item>

</a-col>

</a-row>

<a-row>

<a-col :span="6" :offset="1">

<a-form-item label="生效时段" :labelCol="{span: 9}" :wrapper-col="{ span: 12 }" >

<a-select

style="width: 110px;margin-right:8px"

@change="allTime"

v-decorator="['dayType', { rules: [{ required: true}] }]"

>

<a-select-option :value="0">全时段</a-select-option>

<a-select-option :value="1">自定义</a-select-option>

<a-select-option :value="2">非交易日</a-select-option>

</a-select>

</a-form-item>

</a-col>

<a-col :span="10">

<a-form-item>

<a-range-picker

format="YYYY-MM-DD"

style="width: 370px"

:placeholder="['开始日期', '结束日期']"

:disabled="disableds"

:disabled-date="handleData"

v-decorator="['customTime', { rules: [{ type: 'array', required: requiredTime, message: '请选择生效时段!' }] }]"

@blur="customTimeBlur"

/>

</a-form-item>

</a-col>

</a-row>

</div>

</a-form>

</div>

</template>

JavaScritp

<script>

import moment from 'moment'

//要引用ant Design组件

export default {

name: 'CreateRules',

data () {

return {

period: true,

periodDate: false,

disableds: false,

monthDisabled: true,

intervalShow: true,

requiredTime: true,

requiredIntervalTime: true,

requiredDay: true,

endingTime: true,

weekRequired: true,

monthRequired: true,

efficacyState: true,

showVaildTypeInterval: true,

open: false,

open2: false,

timeDisabled: true,

startTime: '00:00',

endTime: '23:59',

alldefaultValue: '全时段',

}

},

beforeCreate () {

this.form = this.$form.createForm(this, { name: 'coordinated' })

},

mounted () {

this.resetForm()

},

methods: {

moment,

handleClose () {

this.open = false

this.open2 = false

},

handleCloseContinuous () {

this.continuousOpen = false

this.continuousOpen2 = false

},

// @blur: 选中日期后失去焦点时效验

// 间隔 效验频率是否在维护时段内

customTimeBlur (e) {

this.form.validateFields(['ruleVaildIntervalTime.interval',

'ruleVaildIntervalTime.exMonthly1',

'ruleVaildIntervalTime.exMonthly2'], (errors, values) => {

if (!errors && e.target.value) {

this.soundEffects(e, values)

}

})

},

// 我这里封装好了一个方法,主要用在两个地方:表单点击选择效验、表单提交时效验(这里表单提交时是传一个空e)

soundEffects (e, values) {

console.log('生效时段效验:', values)

const everyDay = []

const everyDayString = []

const findMonthDay = []

// 拿到开始结束时间的时间戳来对间隔类型继续比较

// 一天的时间戳为:86400000

const startTime = (e === '' ? moment(moment(values.customTime[0]).valueOf()).format('YYYY-MM-DD')

: moment(moment(e.target.value.substring(1, 33)).valueOf()).format('YYYY-MM-DD'))

const endTime = (e === '' ? moment(moment(values.customTime[1]).valueOf()).format('YYYY-MM-DD')

: moment(moment(e.target.value.substring(34, 67)).valueOf()).format('YYYY-MM-DD'))

const formatStartTime = moment(startTime).valueOf() - 86400000

const formatEndTime = moment(endTime).valueOf()

const yearEndDay = []

// 获取每月最后一日(1-30 这样的格式)

for (let i = 0; i < 12; i++) {

yearEndDay.push((i + 1) + '-' + moment(moment().month(i).endOf('month').format('YYYY-MM-DD')).date())

}

// 获取时间戳的每天

for (let i = formatEndTime; i > formatStartTime; i -= 86400000) {

everyDay.push(moment(i).date())

}

// 通过时间戳来获取每月最后一日 (1-30 这样的格式)(时间戳.month()拿到的月是从0开始)

for (let i = formatEndTime; i > formatStartTime; i -= 86400000) {

everyDayString.push((moment(i).month() + 1) + '-' + moment(i).date())

}

// 通过比较上下最后一日来判断 选中每月最后一日是否在指定的日期范围内

yearEndDay.forEach(res => {

if (everyDayString.find(item => item === res) !== undefined) {

findMonthDay.push(everyDayString.find(item => item === res))

}

})

if (values.ruleVaildIntervalTime.interval === '每月') {

if (values.ruleVaildIntervalTime.exMonthly1 === '首日' && everyDay.find(item => item === 1) === undefined ||

values.ruleVaildIntervalTime.exMonthly1 === '几号' &&

everyDay.find(item => item === values.ruleVaildIntervalTime.exMonthly2) === undefined ||

values.ruleVaildIntervalTime.exMonthly1 === '最后一日' && findMonthDay.length === 0

) {

const arr = [{

message: '维护时段不在范围内!',

field: 'customTime'

}]

this.form.setFields({ customTime: { value: [], errors: arr } })

this.efficacyState = false

} else {

this.efficacyState = true

}

} else {

this.efficacyState = true

}

// 这里主要用到表单提交时效验是否通过进行传参

if (this.efficacyState) {

this.$emit('getResult2', values, true)

} else {

this.$emit('getResult2', values, false)

}

},

// 时间约束(时分)

changeTime (val, dateStrings, type) {

if (type === 'startTime') {

this.startTime = dateStrings

} else {

this.endTime = dateStrings

}

},

getDisabledHours () {

if (this.timeDisabled) {

const hours = []

const time = this.startTime

const timeArr = time.split(':')

for (let i = 0; i < parseInt(timeArr[0]); i++) {

hours.push(i)

}

return hours

} else {

return []

}

},

getDisabledMinutes (selectedHour) {

if (this.timeDisabled) {

const time = this.startTime

const timeArr = time.split(':')

const minutes = []

if (selectedHour === parseInt(timeArr[0])) {

for (let i = 0; i < parseInt(timeArr[1]) + 1; i++) {

minutes.push(i)

}

}

return minutes

} else {

return []

}

},

handleData (current) {

return current && current + 1 < moment().endOf('day').subtract(1, 'day')

},

allTime (val) {

if (val === 0) {

console.log('全时段')

this.disableds = true

this.requiredTime = false

this.alldefaultValue = '全时段'

// 这里form表单提交时 数据不能为null、undefined,不然传值的时候全部值都为空

// this.form.resetFields('customTime', [])

this.form.setFields({ 'customTime': { value: [] } })

} else if (val === 1) {

console.log('自定义')

this.disableds = false

this.requiredTime = true

this.alldefaultValue = '自定义'

} else {

console.log('非交易日')

this.disableds = false

this.requiredTime = true

this.alldefaultValue = '非交易日'

}

},

resetForm () {

this.$nextTick(() => {

this.form.setFieldsValue({

// 维护状态form表绑定值,可以是一个自定义对象

ruleVaildIntervalTime: {

interval: '每周',

exWeekly: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],

exMonthly1: '',

exMonthly2: '',

exDateTimeOnt: moment('00:00', 'HH:mm'),

exDateTimeTwo: moment('23:59', 'HH:mm'),

},

customTime: [],

dayType: 0,

})

})

},

intervalPeriod (val) {

if (val.target.value === '每日') {

this.period = false

this.periodDate = false

this.weekRequired = false

this.monthRequired = false

} else if (val.target.value === '每周') {

this.period = true

this.periodDate = false

this.weekRequired = true

this.monthRequired = false

} else if (val.target.value === '每月') {

this.period = false

this.periodDate = true

this.weekRequired = false

this.monthRequired = true

}

},

periodType (val) {

if (val.target.value === '几号') {

this.monthDisabled = false

this.requiredDay = true

} else {

this.monthDisabled = true

this.requiredDay = false

}

},

// 提交哦(提交的话,自己自定义添加的效验,提交时应该在效验一次,例: this.soundEffects(e, values)这个方法)

handleSubmit () {

this.form.validateFields((err, values) => {

console.log('Received values of form: ', values)

// 这里的提交效验(自己自定义的效验)我就不写了

})

}

}

}

</script>

 v-if导致的表单不能效验问题

(很多时候在操作v-if、v-show的时候会使得表单中的自动效验未能生效)

  • 使用v-if:v-if用来切换的元素是会被销毁的,导致了v-if内的表单项,由于在mounted时期没有进行渲染,所以规则也没有绑定上。
    初始化时不符合显示条件的不会生成规则,导致后面切换条件,显示的输入框的校验不会生效

  • 使用v-show:初始化时会生成所有的规则,即使隐藏了也会进行规则校验

 方法:全部改为v-show

form表单api:   https://www.antdv.com/components/form-cn/#API

 (表单用法差不多就这些,如果有那些看不懂或者有疑惑都有下方留言!)

以上是 Ant Design of Vue a-form表单效验用法(二) 的全部内容, 来源链接: utcz.com/z/374925.html

回到顶部