使用Vuelidate

时间:2019-09-29 16:46:37

标签: vue.js vuejs2 vue-component vuelidate

我似乎无法在Vuelidate的文档中找到如何验证整个模型(包括子组件)的方法。验证父组件和每个子组件不是问题,但是我找不到使用父组件中的validations结构验证子组件的方法。

我认为必须将某些内容作为道具传递给子组件。

我在SO上找到了类似的question,但答案似乎并不完整,不幸的是,它没有帮助。

父组件:

validations: {
    payload: {
        name: {
            required,
            minLength: minLength(5)
        },
        description: {
            required,
            minLength: minLength(20)
        },
        // I assume that this should work if I want to perform validation from the parent component
        blocks: {
            $each: {
                priority: {
                    required,
                    integer,
                    between: between(-999, 999)
                },
                maxProcessed: {

                    minValue: minValue(1)
                },
                startTime: {
                    required,
                    isTime
                }
            }
        }
    }
}

父组件模板(为简洁起见,省略了部分代码)

                    <div class="message-body">
                        <block  v-for="block in payload.blocks"
                               :key="block.id"
                               :type="'TEMPLATE'"
                               :block="block"
                               :selectedBlockId="selectedItem.block"
                               @selectBlock="selectBlock"
                               @removeBlock="removeBlock"></block>
                    </div>

子组件模板(为简洁起见,省略了部分代码)

    <div class="field">
        <div class="control has-icons-left has-icons-right">
            <input class="input is-small" type="text" placeholder="z.B. 300"
                   :class="{'is-danger':$v.block.priority.$invalid}" v-model="block.priority">
            <span class="icon is-left">
                <i class="fas fa-exclamation"></i>
            </span>
        </div>
        <p class="help is-danger" v-if="!$v.block.priority.required">Priority is required</p>
        <p class="help is-danger" v-if="!($v.block.priority.between && $v.block.priority.integer)">Priority has to be a number between -999 and 999</p>
    </div>

子组件(在子组件中具有验证逻辑)

props: {
        block: {
            type: Object,
            required: true
        }
    },
    validations: {
        block: {
            priority: {
                required,
                integer,
                between: between(-999, 999)
            },
            maxProcessed: {

                minValue: minValue(1)
            },
            startTime: {
                required,
                isTime
            }
        }
    }

0 个答案:

没有答案