Ant-Design-Vue中關於Form組件的使用


1.創建form表單的兩種方式,不同的方式在js中創建表單的方式也不同


 

方式1:一般使用在搜索表單中,只需要雙向綁定數據即可,那就使用這種方法即可

 

<template>
  <a-form >
    <a-form-item label="Note" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-input v-model="queryParam.note"></a-input>
    </a-form-item>
    <a-form-item label="mark" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-input v-model="queryParam.mark"></a-input>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
      <a-button type="primary" html-type="submit" @click="handleSubmit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
  export default {
    name: 'TestForm',
    data () {
      return {
        queryParam:{
          note:'',
          mark:''
        }
      }
    },
    methods: {
      handleSubmit () {
        console.log(this.queryParam)
      }
    }
  }
</script>
View Code

 

方式2:在登錄,或者注冊等等應用場景中使用,需要對表單進行校驗等等操作,請使用這種方法

 

 如果只有圖,那我還怎么寫代碼?怎么復制粘貼?怎么工作?

<template>
  <a-form :form="form" @submit="handleSubmit">
    <a-form-item label="Note" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <!-- 建議使用antd自帶的v-decorator來定義表單項,建議封裝校驗方法,頁面結構更清晰 -->
      <a-input v-decorator="['note', ValidateRules.note]"/>
      <!-- 沒有校驗方法,也可以直接這么寫 -->
      <!-- <a-input v-decorator="['note']"/> -->
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
      <a-button type="primary" html-type="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
  export default {
    name: 'TestForm',
    data () {
      return {
        // 這里是用createForm創建表單,傳入this即可
        form: this.$form.createForm(this),  
        // 后面這個參數是options配置項(可選參數),為啥要設置他,見后面說明
        //form: this.$form.createForm(this, { name: 'loginForm' }),  
        ValidateRules: {
          note: { rules: [{ required: true, message: 'Please input your note!' }] }
        }
      }
    },
    methods: {
      handleSubmit (e) {
        const aa = document.getElementById('note')
        console.log(aa.value)
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
          }
        })
        console.log(this.form.getFieldsValue())
      }
    }
  }
</script>
View Code

 

2.在使用createForm()創建表單的時候,傳入options.name的原因:

圖片太小,請在圖片上點擊右鍵,選擇在新標簽頁中打開即可。

 

 如果按照上面所寫,你定義兩個表單,都有個屬性值叫做gender的話,那他們的id也是相同的,都是 id="gender",按照原則來說,一個頁面不應該有相同的id。可能會導致如下:

const genderDiv = document.getElementById('gender');  // 你在這里獲取id為gender的標簽也會引起歧義,如果當前頁面只有一個form表單,或者多個表單沒有重復字段,不設置name並無影響
console.log(genderDiv.value);  // 你只能打印出來一個表單中的gender的值,另一個表單的值你獲取不到了,因為id設置重復了,覆蓋了

 

3.動態校驗規則:

 

 

<template>
  <a-form :form="form">
    <a-form-item
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol"
      label="Name"
    >
      <a-input
        v-decorator="['username',ValidateRules.username]"
        placeholder="Please input your name"
      />
    </a-form-item>
    <a-form-item
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol"
      label="Nickname"
    >
      <a-input
        v-decorator="['nickname',ValidateRules.nickname]"
        placeholder="Please input your nickname"
      />
    </a-form-item>
    <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol">
      <a-checkbox :checked="checkNick" @change="handleChange">
        Nickname is required
      </a-checkbox>
    </a-form-item>
    <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol">
      <a-button type="primary" @click="check">
        Check
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8 },
  };
  const formTailLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8, offset: 4 },
  };
  export default {
    data() {
      return {
        checkNick: false,   // 雙向綁定的checkbox的狀態
        formItemLayout,   // 表單的label布局和wrapper-col布局
        formTailLayout,
        form: this.$form.createForm(this),    // 創建表單
        ValidateRules:{ // 表單校驗方法,其中nickname的表單校驗規則,由this.checkNick屬性決定
          username:{rules: [{ required: true, message: 'Please input your nickname' }]},
          nickname:{rules: [{ required: this.checkNick, message: 'Please input your nickname' }]}}
      };
    },
    methods: {
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      handleChange(e)  {  //checkbox綁定的change方法,傳入的值為checkbox的狀態true或者false
        this.checkNick = e.target.checked;  // 修改checkNick的值,相當於改變nickname的校驗規則
        this.$nextTick(() => {  // 注意要放入nextTick函數中去
          this.form.validateFields(['nickname'], { force: true });    // 啟動校驗規則,force為強制校驗
        });
      },
    },
  };
</script>
View Code

 

 4.自行處理表單數據

補充:validate-status是form-item的屬性中的校驗狀態屬性,如不設置,則會根據校驗規則自動生成,可選:'success' 'warning' 'error' 'validating

help也是form-item中的屬性,相當於錯誤提示,跟validate-status搭配使用

 

 

 


 

<template>
  <a-form>
    <a-form-item
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      label="Prime between 8 & 12"
      :validate-status="number.validateStatus"
      :help="number.errorMsg || tips"
    >
      <a-input-number :min="8" :max="12" :value="number.value" @change="handleNumberChange" />
    </a-form-item>
  </a-form>
</template>
<script>
  function validatePrimeNumber(number) {
    if (number === 11) {
      return {validateStatus: 'success',errorMsg: null,};
    }
    return { validateStatus: 'error',errorMsg: 'The prime between 8 and 12 is 11!',};
  }
  export default {
    data() {
      return {
        labelCol: { span: 7 },
        wrapperCol: { span: 12 },
        number: {value: 11,},
        tips:'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.',
      };
    },
    methods: {
      handleNumberChange(value) {
        this.number = {
          ...validatePrimeNumber(value),
          value,
        };
      },
    },
  };
</script>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM