iview表单

1.表单如下图所示:

iview表单

<Card style="width:100%">
      <p slot="title">
        员工信息录入
      </p>
      <div style="width:80%;display:flex;justify-content:center">
        <Form
          ref="employeeForm"
          :model="employeeForm"
          :rules="employeeFormRule"
          :label-width="80"
          style="width:50%"
        >
          <FormItem
            label="工号"
            prop="user_number"
          >
            <Input
              v-model="employeeForm.user_number"
              placeholder="请输入工号"
            />
          </FormItem>
          <FormItem
            label="姓名"
            prop="user_name"
          >
            <Input
              v-model="employeeForm.user_name"
              placeholder="请输入姓名"
            />
          </FormItem>
          <FormItem
            label="部门"
            prop="dept_id"
          >
            <Select
              filterable
              clearable
              v-model="employeeForm.dept_id"
              placeholder="请选择部门"
            >
              <Option
                v-for="item in deptList"
                :value="item.value"
                :label="item.label"
                :key="item.value"
              ></Option>
            </Select>
            <div style="margin:20px 0 0 0;">
              (如果部门未在下拉选项中,请按照“xx-xx”的格式填写新的部门名称)
            </div>
          </FormItem>
          <FormItem
            label="新部门名"
            prop="new_dept_name"
          >
            <Input
              type="text"
              v-model="employeeForm.new_dept_name"
            />
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              @click="addPerson('employeeForm')"
            >新增</Button>
            <Button
              type="warning"
              @click="resetForm"
            >重置</Button>
          </FormItem>
        </Form>
      </div>

    </Card>

script中:

data(){
    return{
      employeeForm:{
        user_number:'',//工号
        user_name:'',//姓名
        dept_id:'',//部门id
        new_dept_name:'',//新部门名
      },
      deptList:'',//部门组
      employeeFormRule:{
        user_number:[
          {required:true,message:"请填写工号",trigger:'blur'}
        ],
        user_name:[
          {required:true,message:'请填写姓名',trigger:'blur'}
        ]
      }
    }
  }, 
 methods:{
    addPerson(name){
      this.$refs[name].validate((valid)=>{
        if(valid){
          this.$Message.success('Success!!')
        }else{
          this.$Message.warning('请填写必填项')
        }
      })
    },
    resetForm(name){
      this.$refs[name].resetFields()
    }
  }

需要注意的是:

1.重置表单,需要给表单Form设置ref,然后通过this.$refs[ref名].resetFields()重置表单。

2.当添加表单校验规则时,需要给表单Form设置rules,并在data中定义rule。在提交检验表单时一定要定义函数参数,即绑定的表单ref名。接着通过this.refs[name].validate((valid)=>{})进行后续操作。

上一篇:React —— 组件实例的三大核心属性 state,props,refs


下一篇:vue之$nextTick