赞
踩
当表单的属性为数组时,该怎么校验数组元素的每一项呢?
效果图:
vue 代码
<template> <div style="width: 500px"> <el-form :model="ruleForm" :rules="rules" label-width="100px" ref="ruleForm" > <el-form-item label="书籍推荐" prop="bookRecList"> <div style="display: flex; margin-bottom: 10px"> <el-button type="primary" @click="ruleForm.bookRecList.push('')">添加书籍</el-button> </div> </el-form-item> <div v-for="(item, index) in ruleForm.bookRecList" :key="index"> <!-- rules也可以直接赋值规则, 如: :rules="[ { required: true, message: '书籍名称不能为空', trigger: 'change' }, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'change'} ]" --> <el-form-item :prop="`bookRecList[${index}]`" :rules="rules.book"> <el-input placeholder="请输入内容" v-model="ruleForm.bookRecList[index]" > <span slot="suffix"> {{ item.length }}/10 </span> </el-input> </el-form-item> </div> </el-form> </div> </template> <script> export default { data() { const validBookRecList = (rule, value, callback) => { if (value.length < 1) { callback(new Error("至少推荐一个书籍")); } else { callback(); } }; const validBook = (rule, value, callback) => { console.log(rule); if (value === "" || value === null) { callback(new Error("请输入书籍名称")); } else { if (value.length > 10) { callback(new Error("书籍名称长度不超过10")); } callback(); } }; return { ruleForm: { bookRecList: [""], }, rules: { bookRecList: { validator: validBookRecList, trigger: "change" }, book: { validator: validBook, trigger: "change" }, }, }; }, }; </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。