Vue中使用el-form表格 使表头的内容居中且带有必填字段的红色星号

Vue中使用el-form表格 使表头的内容居中且带有必填字段的红色星号


前言:
element的el-form表单提供了是否显示必填字段的标签旁边的红色星号的样式,但是该样式和标题文字居中显示冲突,两者不可共存,研究了一下element的写法,自己琢磨了一下出了可以文字居中且有红色星号的样式


一、案例

先放上对比图


1、这是没有星号时的样式

在这里插入图片描述


2、这是element-form自带的必填字段的标签旁边的红色星号,可以明显看出文字被挤到右边去了

在这里插入图片描述


3、这是自己研究出来的文字居中且有红色星号的样式

在这里插入图片描述

二、使用步骤

1.引入库

在main.js中引入ElementUI组件:

import ElementUI from 'element-ui'
Vue.use(ElementUI)

2.使用el-form

在需要表单的代码中使用el-form,代码如下(示例):


template的数据

<template>
  <div class="elForm">
  	<!-- hide-required-asterisk 用来隐藏必填字段的标签旁边的红色星号 -->
    <el-form ref="form" :model="form" label-width="70px" :hide-required-asterisk="true">
       <el-form-item lang="zh" label="姓名"
                     :rules="[ { required: true, message: '请输入姓名', trigger: 'blur' },]">
         <!-- 自己写的红色星号样式 -->
         <span class="IsMust">*</span>
         <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
       </el-form-item>
       <!-- 用来对比的样式 -->
       <el-form-item lang="zh" label="姓名">
         <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
       </el-form-item>
       <el-form-item lang="zh" label="曾用名">
         <el-input v-model="form.name" placeholder="请输入曾用名"></el-input>
       </el-form-item>
     </el-form>
  </div>
</template>

script的数据

<script>

export default {
    
    
  data() {
    
    
    return {
    
    
    	form: {
    
    } // 表单绑定的数据
    }
  },
  methods:{
    
    
  },
}
</script>

style的内容

<style lang="scss" scoped>

.elForm{
    
    
  display: flex;
  justify-content: center;
  .IsMust{
    
    
    position: absolute;
    color: #F56C6C;
    // 位置可以根据自己的样式自行调整
    top: 6px;
    left: -83px;
  }
  .el-form{
    
    
    width: 400px;
    .el-input{
    
    
      width: 200px;
    }
    ::v-deep .el-input__inner{
    
    
      width: 200px;
    }
  	.el-form-item{
    
    
  	  position: relative;
  	}
  	::v-deep .el-form-item__label{
    
    
      text-align-last: justify; // 文字左右散开居中
      text-align: justify;
      text-justify: distribute-all-lines; // 这行必加,兼容ie浏览器
      margin-right: 34px;
      padding: 0;
      font-size: 16px;
      line-height: 49px;
      font-weight: 400;
      color: #353E4C;
    }
    ::v-deep .el-form-item__content{
    
    
      line-height: 50px;
    }
  }
}

</style>

总结

1、先给表单项添加rules,使得当前的参数为必填项
2、再修改表单的hide-required-asterisk属性,将原本的必填字段的标签旁边的红色星号隐藏
3、自行添加一个红色星号样式,然后利用position属性给定一个绝对位置

猜你喜欢

转载自blog.csdn.net/Oamnij/article/details/125187967
今日推荐