form组件基于async-validator实现的数据校验,给form设置属性rules,同时给需要校验的formItem设置属性prop指向对应字段即可。可以参考iview表单校验网址:http://v3.iviewui.com/compone...
iview同时也支持异步校验
异步校验的步骤:
1、首先定义一个asyValid方法

async asyValid (rule, value, cb) {
            this.$http.post(vaMetaApi.getMetaDefine, {
                moduleName: 'CFAS',
                metaType: 'billlist',
                name: this.formItem.name
            }).then((response) => {
                if (response.data.code === 0) {
                    cb()
                } else {
                    cb(new Error('标识不能重复'))
                }
            }).catch((e) => {
                this.$Message.error(`校验失败${e}`)
                cb()
            })
        }

2、接着写校验条件,将上面的方法写到validator中。

ruleadd: {
                name: [{
                    required: true,
                    trigger: 'blur',
                    validator: (rule, value, cb) => {
                        this.asyValid(rule, value, cb)
                    }
                }]
            }

代码实例:

<template>
    <Form :model="formItem" :label-width="65" :rules="ruleadd" ref="formItem">
        <FormItem label="标识" prop="name">
          <Input v-model.trim="formItem.name" placeholder="输入标识"/>
        </FormItem>
        <FormItem label="名称">
          <Input v-model.trim="formItem.title" placeholder="输入名称"/>
        </FormItem>
    </Form>
</template>
<script>
import {vaMetaApi} from '../../api'
export default {
    name: 'AddMeta',
    data () {
        return {
            formItem: {
                name: '',
                title: ''
            },
            ruleadd: {
                name: [{
                    required: true,
                    trigger: 'blur',
                    validator: (rule, value, cb) => {
                        this.asyValid(rule, value, cb)
                    }
                }]
            }
        }
    },
    methods: {
        async asyValid (rule, value, cb) {
            this.$http.post(vaMetaApi.getMetaDefine, {
                moduleName: 'CFAS',
                metaType: 'billlist',
                name: this.formItem.name
            }).then((response) => {
                if (response.data.code === 0) {
                    cb()
                } else {
                    cb(new Error('标识不能重复'))
                }
            }).catch((e) => {
                this.$Message.error(`校验失败${e}`)
                cb()
            })
        }
    }
}
</script>

666888
334 声望10 粉丝

知其然且知其所以然。