写云盘的创建文件夹功能时,需要在前段添加一个重名校验,由于前段UI用的是element,就研究了一下element自带的表单校验中自定义校验规则。
为表单新增一条rules:
{ required: true, message: '目录已存在', validator: this.checkExistName, trigger: 'blur' }
checkExistName函数这么写:
// 创建文件夹之前重名校验
checkExistName(rule, value, callback) {
listFile(this.bucketID, {cur_dir: this.currentPath}).then((res) => {
let objs = res.data
for (let i in objs) {
if (objs[i].is_dir && objs[i].name === value) {
return callback(new Error('目录已存在'))
}
}
})
},
listFile是向后端接口请求文件列表的函数,不重要。
效果如下: