欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ant?design?vue的form表單取值方法

 更新時(shí)間:2022年06月01日 09:10:48   作者:等鯨落  
這篇文章主要介紹了ant?design?vue的form表單取值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

ant design vue的form表單取值

官方中有以下兩種取值方式

 因?yàn)椴皇呛苁煜?,所以還是查了文檔找了一下使用方式,剛開始查到的文檔是這樣寫的

 然后返回了undefined,后來又查詢了一些文檔,發(fā)現(xiàn)我多加了一個(gè)props屬性,然后使用第二個(gè)方法成功了,代碼如下:

ant design of vue 學(xué)習(xí)之表單form

v-decorator(表單驗(yàn)證,內(nèi)置綁定,初始值)

1、可通過 v-decorator 進(jìn)行表單驗(yàn)證

//內(nèi)置驗(yàn)證規(guī)則
<a-form-item label="課程名稱"
? ? ? ? ? ? ?v-bind="formItemLayout">
? ?<a-input placeholder="課程名稱"
? ? ? ? ? ? v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項(xiàng),最大50字符' }] }]" />
</a-form-item>
//自定義驗(yàn)證規(guī)則01
<a-form-item>
? <a-input size="large"
? ? ? ? ? ?type="text"
? ? ? ? ? ?placeholder="手機(jī)號(hào)"
? ? ? ? ? ?v-decorator="['mobileNumber',?
? ? ? ? ? ?{rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '請(qǐng)輸入正確的手機(jī)號(hào)' }], validateTrigger: 'change'}]">
? ? <a-icon slot="prefix"
? ? ? ? ? ? type="mobile"
? ? ? ? ? ? :style="{ color: 'rgba(0,0,0,.25)' }" />
? </a-input>
</a-form-item>
//自定義驗(yàn)證規(guī)則02
<a-form-item ? v-bind="formItemLayout"
?? ? ? ? ? ? ? label="手機(jī)號(hào)碼">
?? ? <a-input placeholder="手機(jī)號(hào)碼"
?? ? ? ? ? ? ?v-decorator="['mobileNumber',{rules: [{ required: true,max:11,message:'請(qǐng)輸入正確格式的手機(jī)號(hào)碼',validator:MobileNumberValidator}]}]" />
</a-form-item>
//在methods中設(shè)定方法
// 手機(jī)號(hào)驗(yàn)證
MobileNumberValidator (rule, value, callback) {
? const idcardReg = /^1(3|4|5|6|7|8|9)\d{9}$/
? if (!idcardReg.test(value)) {
? ? // eslint-disable-next-line standard/no-callback-literal
? ? callback('非法格式')
? }
? // Note: 必須總是返回一個(gè) callback,否則 validateFieldsAndScroll 無法響應(yīng)
? callback()
}

2、可通過 v-decorator 進(jìn)行內(nèi)置的雙向綁定(詳情可看下文的數(shù)據(jù)獲取與填充)

數(shù)據(jù)填充(所有項(xiàng)) ? this.form.setFieldsValue(data)
數(shù)據(jù)獲?。ㄋ许?xiàng)) ? this.form.validateFields(async (errors, values) => {
?? ??? ??? ??? ??? ??? ? ?console.log(values)
?? ??? ??? ??? ??? ?});

3、可通過 v-decorator 的initialValue設(shè)置初始值

<a-form-item label="課程名稱"
? ? ? ? ? ? ?v-bind="formItemLayout">
? ?<a-input placeholder="課程名稱"
? ? ? ? ? ? v-decorator="['name', { initialValue:'姚峰', rules: [{ required: true, max: 50, message: '必填項(xiàng),最大50字符' }] }]" />
</a-form-item>

4、下拉選擇框的 labelInValue 屬性

通常情況下,通過this.form.getFieldValue(“courseTeacherList”),你只能獲取一個(gè)數(shù)組包含value值,形如[‘7’,‘10’],而通過labelInValue屬性可以得到[{key: “7”,label: “王鳳”},{{key: “10”,label: “姚峰”}}]

  • key表示value
  • label表示顯示值
<a-form-item label="教師"
             v-bind="formItemLayout">
  <a-select mode="multiple"
  			labelInValue
            placeholder="請(qǐng)選擇教師"
            v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項(xiàng),請(qǐng)選擇教師' }] }]">
	<a-select-option v-for="item in teacherList"
	                 :key="item.id"
	                 :value="item.id">{{ item.name }}</a-select-option>
  </a-select>
</a-form-item>              

5、type類型檢驗(yàn)

Type
    string: Must be of type string. This is the default type.
    number: Must be of type number.
    boolean: Must be of type boolean.
    method: Must be of type function.
    regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
    integer: Must be of type number and an integer.
    float: Must be of type number and a floating point number.
    array: Must be an array as determined by Array.isArray.
    object: Must be of type object and not Array.isArray.
    enum: Value must exist in the enum.
    date: Value must be valid as determined by Date
    url: Must be of type url.
    hex: Must be of type hex.
    email: Must be of type email.
    any: Can be any type.

數(shù)據(jù)獲取與填充

//獲取一個(gè)輸入控件的值  Function(fieldName: string)
let myDate = this.form.getFieldValue("startDate");
//獲取一組輸入控件的值,如不傳入?yún)?shù),則獲取全部組件的值   Function([fieldNames: string[]])
let value = this.form.getFieldsValue(["startDate","endDate"]);
let value = this.form.getFieldsValue();
//設(shè)置一組輸入控件的值
this.form.setFieldsValue({
	startDate:res.result["startDate"],
	endDate:res.result["endDate"],
})
//設(shè)置一組輸入控件的值  加了labelInValue屬性
this.form.setFieldsValue({
	userName:{
		label:res.result["userName"],
		key:res.result["userNameId"]
	}
})
//設(shè)置表單數(shù)據(jù)  對(duì)日期、下拉框含labelInValue屬性的form控件的數(shù)據(jù)設(shè)置要特殊處理才能綁定
//對(duì)于日期控件需要將string類型的數(shù)據(jù)轉(zhuǎn)換moment類型
//對(duì)于下拉框含labelInValue屬性控件,數(shù)據(jù)需要轉(zhuǎn)換成key、label的對(duì)象格式
import moment from 'moment'
setFormValues (record) {
  // 控制教師
   if (courseTeacherList && courseTeacherList.length > 0) {
     record['courseTeacherList'] = courseTeacherList.map(item => ({
       key: item.teacherId + '',
       label: item.teacherName
     }))
   }
  const fields = ['courseTeacherList', 'certificateNo', 'cardTime', 'termValidity', 'documentStatus', 'remark']
  Object.keys(record).forEach((key) => {
    if (fields.indexOf(key) !== -1) {
      this.form.getFieldDecorator(key)
      const obj = {}
      if (key === 'cardTime' && record['cardTime'] != undefined) {
        obj[key] = moment(data[key], 'YYYY-MM-DD')
      } else {
        obj[key] = record[key]
      }
      this.form.setFieldsValue(obj)
    }
  })
},
//關(guān)閉表單清空表單數(shù)據(jù)
this.form.resetFields();
//提交表單獲取數(shù)據(jù)
//通過this.form.validateFields函數(shù)進(jìn)行表單驗(yàn)證以及數(shù)據(jù)獲取
//對(duì)于日期控件,獲取的是moment類型數(shù)據(jù),需要轉(zhuǎn)換成字符串儲(chǔ)存,
//形如values.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD') : ''
handleSubmit () {
  const { id } = this
  this.form.validateFields((err, values) => {
    if (!err) {
      this.submitLoading = true
      values.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD') : ''
      // 處理教師
      values.courseTeacherList = values.courseTeacherList.map(item => {
        const obj = {}
        obj.teacherId = Number(item.key)
        return obj
      })
      if (id) {
        // 修改
        updateCourse({ id, ...values }).then(res => {
          if (res.code == 0) {
            this.$message.success('保存成功')
            this.form.resetFields()
            this.$router.back()
          } else {
            this.$message.error('保存失敗,請(qǐng)稍后再試')
          }
        }).finally(() => {
          this.submitLoading = false
        })  
    } else {
        // 添加
        addCourse(values).then(res => {
          if (res.code == 0) {
            this.$message.success('保存成功')
            this.form.resetFields()
            this.$router.back()  
          } else {
            this.$message.error('保存失敗,請(qǐng)稍后再試')
          }
        }).finally(() => {
          this.submitLoading = false
        })
      }
    }
  })
},    

表單實(shí)例

<template>
  <div>
    <a-card>
      <a-form :form="form">
      	<!-- 文本框 -->
        <a-form-item label="課程名稱"
                     v-bind="formItemLayout">
          <a-input placeholder="課程名稱"
                   v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項(xiàng),最大50字符' }] }]" />
        </a-form-item>
        <a-form-item label="教師"
                     v-bind="formItemLayout">
          <a-select mode="multiple"
                    labelInValue
                    placeholder="請(qǐng)選擇教師"
                    v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項(xiàng),請(qǐng)選擇教師' }] }]">
            <a-select-option v-for="item in teacherList"
                             :key="item.id"
                             :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 文本域 -->
        <a-form-item label="課程簡(jiǎn)介"
                     v-bind="formItemLayout">
          <a-textarea placeholder="課程簡(jiǎn)介"
                      :autosize="{ minRows: 6, maxRows: 10 }"
                      v-decorator="['introduction', { rules: [{ required: true, max: 1000, message: '必填項(xiàng),最大1000字符' }] }]" />
        </a-form-item>
        <!-- 步進(jìn)器 -->
        <a-form-item label="時(shí)長"
                     v-bind="formItemLayout">
          <a-input-number v-decorator="['timeLength',{initialValue:60,rules:[{required:true,message:'必填'}]}]"
          :min="1"
                          :max="100"
                          :precision="0" />
        </a-form-item>
        <!-- 日期控件 -->
        <a-form-item label="開課日期"
                     v-bind="formItemLayout">
          <a-date-picker v-decorator="['startDate', { rules: [{ type: 'object', required: true, message: '請(qǐng)選擇開課日期' }] }]"
                         format="YYYY-MM-DD" />
        </a-form-item>
        <!-- 開關(guān)滑塊 -->
        <a-form-item label="在線課程"
                     v-bind="formItemLayout">
          <a-switch checkedChildren="是"
                    unCheckedChildren="否"
                     v-decorator="['online', { valuePropName: 'checked', initialValue: true }]" />
        </a-form-item>
        <!-- 單選框 -->
        <a-form-item label="是否發(fā)布"
                     v-bind="formItemLayout">
          <a-radio-group name="radioGroup"
          				 v-decorator="['publish', { initialValue: 1 }]">
            <a-radio :value="1">發(fā)布</a-radio>
            <a-radio :value="0">不發(fā)布</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <a-row>
        <a-col :span="14"
               :offset="5"
               style="text-align: center;">
          <a-button :loading="submitLoading"
          			style="margin-left: 16px"
                    type="primary"
                    @click="handleSubmit">保存</a-button>
          <a-button style="margin-left: 16px"
                    @click="back">返回</a-button>
        </a-col>
       </a-row>
    </a-card>
  </div>
</template>
import moment from 'moment'
import { addCourse, getTeacherList, getCourseById, updateCourse } from '@/api/learning/course'
export default {
  data () {
    return {
      submitLoading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          lg: { span: 7 },
          sm: { span: 7 }
        },
        wrapperCol: {
          lg: { span: 10 },
          sm: { span: 17 }
        }
      },
      teacherList: [],
      unitSn: ''
    }
  },
  created () {
    // 獲取教師列表
    this.getTeacherList()
    // 獲取詳情
    if (this.id) {
      this.getInfo()
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    }
  },
  methods: {
    // 獲取教師列表
    getTeacherList () {
      const unitSn = this.unitSn || this.$store.getters.userInfo.unitSn
      const params = {
        current: 1,
        size: -1,
        unitSn
      }
      getTeacherList(params).then(res => {
        if (res.code == 0) {
          if (res.data.records.length > 0) {
            this.teacherList = res.data.records.map(item => {
              const obj = {}
              obj.id = item.id + ''
              obj.name = item.name
              return obj
            })
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 獲取詳情 設(shè)置表單數(shù)據(jù)
    getInfo () {
      let { id } = this
      id = Number(id)
      getCourseById(id).then(res => {
        if (res.code == 0) {
          this.setFormValues({ ...res.data })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 設(shè)置表單數(shù)據(jù)
    setFormValues (record) {
      const { courseTeacherList, unitSn } = record
      this.unitSn = unitSn
      // 控制教師
      if (courseTeacherList && courseTeacherList.length > 0) {
        record['courseTeacherList'] = courseTeacherList.map(item => ({
          key: item.teacherId + '',
          label: item.teacherName
        }))
      }
      const fields = ['name', 'courseTeacherList', 'introduction', 'timeLength', 'startDate', 'online', 'publish']
      Object.keys(record).forEach(key => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          const obj = {}
          if (key === 'startDate' && record['startDate'] != undefined) {
            obj[key] = moment(record[key], 'YYYY-MM-DD')
          } else {
            obj[key] = record[key]
          }
          this.form.setFieldsValue(obj)
        }
      })
    },
    // 保存
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const { id } = this
          this.submitLoading = true
          // 處理教師
          values.courseTeacherList = values.courseTeacherList.map(item => {
            const obj = {}
            obj.teacherId = Number(item.key)
            return obj
          })
          // 處理日期
          values.startDate = values.startDate ? values.startDate.format('YYYY-MM-DD') : ''
          if (id) {
            // 修改
            updateCourse({ id, ...values }).then(res => {
              if (res.code == 0) {
                this.$message.success('保存成功')
                this.form.resetFields()
                this.$router.back()
              } else {
                this.$message.error('保存失敗,請(qǐng)稍后再試')
              }
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            // 添加
            addCourse(values).then(res => {
              if (res.code == 0) {
                this.$message.success('保存成功')
                this.form.resetFields()
                this.$router.back()
              } else {
                this.$message.error('保存失敗,請(qǐng)稍后再試')
              }
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },
    // 返回
    back () {
      this.$confirm({
        title: '還未保存,是否返回上一級(jí)?',
        okText: '確認(rèn)返回',
        cancelText: '取消',
        onOk: () => {
          this.$router.back()
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。 

相關(guān)文章

  • vue.js實(shí)現(xiàn)二級(jí)菜單效果

    vue.js實(shí)現(xiàn)二級(jí)菜單效果

    這篇文章主要為大家詳細(xì)介紹了vue.js實(shí)現(xiàn)二級(jí)菜單效果的具體方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-10-10
  • Vue axios 中提交表單數(shù)據(jù)(含上傳文件)

    Vue axios 中提交表單數(shù)據(jù)(含上傳文件)

    本篇文章主要介紹了Vue axios 中提交表單數(shù)據(jù)(含上傳文件),具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-07-07
  • vue以組件或者插件的形式實(shí)現(xiàn)throttle或者debounce

    vue以組件或者插件的形式實(shí)現(xiàn)throttle或者debounce

    這篇文章主要介紹了vue以組件或者插件的形式實(shí)現(xiàn)throttle或者debounce,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-05-05
  • vue.js?diff算法原理詳細(xì)解析

    vue.js?diff算法原理詳細(xì)解析

    這篇文章主要介紹了vue.js?diff算法原理詳細(xì)解析,diff算法可以看作是一種對(duì)比算法,對(duì)比的對(duì)象是新舊虛擬Dom。顧名思義,diff算法可以找到新舊虛擬Dom之間的差異,但diff算法中其實(shí)并不是只有對(duì)比虛擬Dom,還有根據(jù)對(duì)比后的結(jié)果更新真實(shí)Dom
    2022-06-06
  • Vue3優(yōu)雅的實(shí)現(xiàn)跨組件通信的常用方法總結(jié)

    Vue3優(yōu)雅的實(shí)現(xiàn)跨組件通信的常用方法總結(jié)

    開發(fā)中經(jīng)常會(huì)遇到跨組件通信的場(chǎng)景,props?逐層傳遞的方法實(shí)在是太不優(yōu)雅了,所以今天總結(jié)下可以更加簡(jiǎn)單的跨組件通信的一些方法,文中通過代碼實(shí)例講解的非常詳細(xì),需要的朋友可以參考下
    2023-11-11
  • 詳解Vue.js 作用域、slot用法(單個(gè)slot、具名slot)

    詳解Vue.js 作用域、slot用法(單個(gè)slot、具名slot)

    這篇文章主要介紹了Vue.js 作用域、slot用法(單個(gè)slot、具名slot),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • 基于vue-cli 路由 實(shí)現(xiàn)類似tab切換效果(vue 2.0)

    基于vue-cli 路由 實(shí)現(xiàn)類似tab切換效果(vue 2.0)

    這篇文章主要介紹了基于vue-cli 路由 實(shí)現(xiàn)類似tab切換效果(vue 2.0),非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下
    2019-05-05
  • vue和better-scroll實(shí)現(xiàn)列表左右聯(lián)動(dòng)效果詳解

    vue和better-scroll實(shí)現(xiàn)列表左右聯(lián)動(dòng)效果詳解

    這篇文章主要介紹了vue和better-scroll實(shí)現(xiàn)列表左右聯(lián)動(dòng)效果,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Vue ​v-model相關(guān)知識(shí)總結(jié)

    Vue ​v-model相關(guān)知識(shí)總結(jié)

    這篇文章主要介紹了Vue &#8203;v-model相關(guān)知識(shí)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用vue框架,感興趣的朋友可以了解下
    2021-01-01
  • vue表格(table)計(jì)算總計(jì)方式

    vue表格(table)計(jì)算總計(jì)方式

    這篇文章主要介紹了vue表格(table)計(jì)算總計(jì)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07

最新評(píng)論