vue2的form利用插槽修改错误提示UI

1. 需求

很多时候我们使用el-form想修改下错误提示的UI,比如table中使用form校验这类场景下错误提示的UI调整就非常重要。

2. 了解文档

Form-Item Scoped Slot

name 说明
error 自定义表单校验信息的显示方式,参数为 { error }

3.实际使用

html里使用错误的插槽将自定义错误插入。

<template>
	<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" >
	  <el-form-item label="活动名称" prop="name">
	    <el-input v-model="ruleForm.name"></el-input>
	    <template slot="error" slot-scope="itemScope">
	        <!-- 自定义错误信息 -->
	        <div v-if="itemScope.error">
	            <el-tooltip :content="itemScope.error" placement="top">
	                <i class="el-icon-warning-outline sad-item-error" />
	            </el-tooltip>
	         </div>
       </template>
	  </el-form-item>
	  <el-form-item>
	    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
	    <el-button @click="resetForm('ruleForm')">重置</el-button>
	  </el-form-item>
	<el-form>
</template>

javascript的代码大同小异

export default {
    data() {
      return {
        ruleForm: {
          name: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }

样式要做一些调整

.el-form-item{
  margin-bottom: 0;
}
/* 自己调整 */
.sad-item-error{
  position: absolute;
  color: #F56C6C;
  top: 0;
  left: 100%;
  line-height: 32px;
}

4. 结果

结果类似如下:
在这里插入图片描述

相关推荐

  1. vue

    2024-06-06 16:18:04       48 阅读
  2. Vue2/Vue3-(全)

    2024-06-06 16:18:04       58 阅读
  3. VUE介绍

    2024-06-06 16:18:04       45 阅读
  4. Vue网络请求、Vuex

    2024-06-06 16:18:04       64 阅读
  5. vue2 实战:作用域

    2024-06-06 16:18:04       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-06 16:18:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-06 16:18:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-06 16:18:04       82 阅读
  4. Python语言-面向对象

    2024-06-06 16:18:04       91 阅读

热门阅读

  1. 【源码】SpringBoot事务注册原理

    2024-06-06 16:18:04       25 阅读
  2. 【ubuntu】增加samba服务和文件夹

    2024-06-06 16:18:04       31 阅读
  3. Vue 2集成Ant Design步骤

    2024-06-06 16:18:04       26 阅读
  4. 134. 加油站

    2024-06-06 16:18:04       27 阅读
  5. XML读写

    2024-06-06 16:18:04       26 阅读
  6. VScode中Markdown图片尺寸大小调整

    2024-06-06 16:18:04       31 阅读
  7. vue课后习题及答案

    2024-06-06 16:18:04       29 阅读
  8. Vue+Django上传文件

    2024-06-06 16:18:04       31 阅读
  9. 596. 超过5名学生的课

    2024-06-06 16:18:04       28 阅读