a-form-model的简单例子

<template>
  <div>
    <a-form-model :model="dataForm" ref="dataForm" :rules ="rules">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="姓名" prop="name">
            <a-input v-model="dataForm.name" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="性别" prop="sex">
            <a-select v-model="dataForm.sex" @change="onChange">
              <a-select-option :value="undefined">请选择</a-select-option>
              <a-select-option v-for="(item, key) in options" :key="key" :value="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="住址" prop="address">
            <a-input v-model="dataForm.address" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-button @click="handleSubmit()">提交</a-button>
  </div>
</template>

<script>

  export default {
    data() {
      const regAddress = (rule, value, callback) =>{
        if (!value) {
          callback(new Error('请输入住址!'))
        } else {
          callback()
        }
      }
      return {
        options:[{value:'nan',text:'男'},{value:'nv',text:'女'}],
        dataForm: {},
        rules:{
          name: [
            { required: true, message: '请输入姓名', trigger: 'change' },
            { min: 3, max: 5, message: '长度在3到5之间', trigger: 'change' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change'},
          ],
          address: [
            { required: true, validator:regAddress, trigger: 'change'},
          ]
        }
      }
    },
    created(){
      this.loadData();
    },
    methods:{
      loadData(){
        let record = {};
        record.name = "Alley";
        record.address = "河南省郑州市中原区";
        this.dataForm = Object.assign({}, record);
      },
      onChange(e){
        console.log(e)
      },
      //提交校验
      handleSubmit() {
        let _this = this;
        let queryParams = Object.assign({}, this.dataForm);
        console.log("======================")
        console.log(queryParams);
        console.log(queryParams.name);
        console.log(queryParams.sex);
        console.log(queryParams.address);
        console.log("======================")
        _this.$refs.dataForm.validate(valid => {
          if (valid) {
            _this.loading = true;
            //this.$refs.dataForm.resetFields();
            _this.clearForm(); //清除表单内容
            this.$message.success('提交成功!');
          } else {
            return false;
          }
        });
      },
      clearForm(){
        this.dataForm = {};
      },
    }
  }

</script>
posted @ 2022-06-14 10:21  岁月淡忘了谁  阅读(1570)  评论(0编辑  收藏  举报