当前位置:   article > 正文

AntVue a-form表单比较坑的地方_ant-design-vue4 form表单

ant-design-vue4 form表单

AntDesignVue,需要注意的一些组件

form 表单

ant design vue官网中,form表单分别有以下两种方式
一、v-decorator方式的绑定(第一次用,坑多)

data(){
	return {
		form: this.$form.createForm(this, { name: 'form_monitor_task' }),
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5

1、v-decorator绑定啥变量,校验传参就是啥,如果不一致,可以重新写变量,如下方式:

 a-form(layout="inline" :form="form")
     a-form-item(label='任务名称')
       a-input(
         v-decorator="['name',{ rules: [{ required: true, message: '请输入任务名称' }] }]",
         placeholder="请输入任务名称",
         style="width: 160px"
       )
     a-form-item(label='监测类型')
       a-select(
         allowClear,
         v-decorator="['type',{ rules: [{ required: true, message: '请选择监测类型' }] }]",
         placeholder="请选择监测类型",
         style="width: 160px",
         :filterOption="false",
         :notFoundContent="null"
         @change="changeMonitorType"
       )
         a-select-option(
           v-for="item in queryOption.monitorTypeOption",
           :key="item.id"
           :value="item.id",
           :label="item.name"
         ) {{ item.name }}
     a-form-item(label='监测周期')
       a-range-picker(
         style="width: 250px",
         :format="dateFormat"
         v-decorator="['period', { rules: [{ required: true, message: '请选择监测周期' }] }]",
       )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
this.form.validateFields(async (err, values) => {
        if (!err) {
          if(this.dialogStatus == 0){
            // 新增
            let param = {
              name: values.name,
              type: values.type,
              platform: values.platform,
              carry_stuff_type: values.carry_stuff_type,
              followers: values.followers,
              streamer_ids: values.streamer_ids.join(','), // 绑定了id值
              account_names: this.account_names.join(','), // 名称
              start_time: moment(values.period[0]).format('YYYY-MM-DD'),
              end_time: moment(values.period[1]).format('YYYY-MM-DD')
            }
            const res = await setAddTaskApi(param)
            if(res.code==1000){
              this.isShowAddDialog = false
              this.$message.success(res.message)
              this.fetchList()
              // 手动清除表单条件
              this.form.resetFields()
            }else{
              this.$message.error(res.message)
            }
            
          }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

2、 a-select 模糊查询、多选

a-form-item(label='直播间名称')
       a-select(
         showSearch
         :filterOption="filterStreamerOption"
         mode="multiple"
         v-decorator="['streamer_ids']"
         placeholder="请输入直播间名称"
         style="width: 160px"
         @change="changeVideoName"
       )
         a-select-option(
           v-for="item in queryOption.videoNameOption" 
           :key="item.id"
           :value="item.id"
           :label="item.name"
         ) {{ item.name }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
 filterStreamerOption(value, option){
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
  • 1
  • 2
  • 3

3、必填项控制
一般用rules搞定,但是有一些需要动态控制

<a-cascader
   v-decorator="['category_id',{rules:rules.category_id}]"
   placeholder="请选择商品分类"
   allowClear
   :options="categoryOptions"
   :fieldNames="categoryFieldNames"
   expandTrigger="hover"
   style="width:210px"
   @change="onChangeCategory"
 ></a-cascader>
 <a-button-group 
    v-decorator="['data_deal', {rules: rules.data_deal}]">
    <a-button 
      v-for="(item,index) in clueDetail.operations.actions" 
      :key="index"
      :type="item.action==curAction?'primary':''"
      @click="handleDataDeal(item)"
    >
      {{item.name}}
    </a-button>
  </a-button-group>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
data(){
	return {
	  curAction: '', //当前选中的按钮
      rules: {
        category_id: [{ required: true, message: '请选择商品分类' }],
        data_deal: [{required: true, validator: this.isCheckDealBtn}],//动态校验
      }
    }
},
methods:{
	isCheckDealBtn(rule, value, callback){
      if (!this.curAction) {
        callback('请选择数据处理方式');
      } else {
        callback();
      }
    },

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

4、v-decorator 回填数据(一般编辑的时候),以及清空表单数据
注意回填一定是this.$nextTick,this.form.setFieldsValue,清空 this.form.resetFields() 怎么添加怎么清除

async handleEdit(record){
      // 日期回填格式 根据后端的时间戳秒 转换为 年-月日
      let start_time = record.start_time?record.start_time:0 //167297468
      let end_time = record.end_time?record.end_time:0
      let startTime = moment(start_time * 1000).format('YYYY-MM-DD')
      let endTime = moment(end_time * 1000).format('YYYY-MM-DD')

      // 回填数据
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: record.name?record.name:undefined,
          type: record.type?record.type:undefined,
          platform: record.platform?record.platform:undefined,
          carry_stuff_type: record.carry_stuff_type?record.carry_stuff_type:undefined,
          followers: record.followers?record.followers:undefined,
          streamer_ids: record.streamer_ids?record.streamer_ids:undefined,
          period: [moment(startTime, this.dateFormat), moment(endTime, this.dateFormat)]
        });
      })

      // 直播间的中文名称
      this.account_names = record.account_names
    },
// 清空 
this.form.resetFields()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

二、v-model方式的绑定(以前经常用,还算顺手)
v-model 绑定的变量,直接可以回填,不需要像v-decorator设置(this.form.setFieldsValue)回填内容,所以我认为比较方便

a-form-model(
 ref="ruleForm"
 :model="form"
 :rules="rules"
 :label-col="labelCol"
 :wrapper-col="wrapperCol")
 a-form-model-item(ref="advert_id" label="广告id" prop="advert_id")
   a-input(v-model="form.advert_id" disabled)
 a-form-model-item(ref="collect_time" label="采集时间" prop="collect_time")
   a-date-picker(
     disabled
     v-model="form.collect_time" 
     placeholder="请输入采集时间"
     format="YYYY-MM-DD HH:mm:ss"
     )
 a-form-model-item(ref="range_time" label="时间范围")
   a-range-picker(
     disabled
     v-model="form.range_time" 
     placeholder="请输入采集时间"
     format="YYYY-MM-DD"
     )
 a-form-model-item(ref="category_id" label="广告类别" prop="category_id")
   a-cascader(
     disabled
     :showSearch="true",
     v-model="form.category_id",
     :options="queryOption.category",
     :fieldNames="{ label: 'name', value: 'id', children: 'subs' }",
     expandTrigger="hover",
     placeholder="按照广告类别选择"
   )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
export default {
  data(){
    return {
      moment,
      labelCol: { span: 6 },
      wrapperCol: { span: 15 },
      form: {
        advert_id:'',
        collect_time: null,
        category_id: [],
        range_time: null
      },
      rules: {
        title: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
        collect_time:[{ required: true, message: '请输入采集时间', trigger: 'blur' }],
        category_id: [{ required: true, message: '请输入广告类别', trigger: 'blur' }]
      },
      queryOption: {
        category: [], // 广告类别
      }
    }
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
async handleSure(){
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let param = {
            advert_id: this.form.advert_id,
            collect_time: this.form.collect_time,
            category_id: this.form.category_id
          }
          const res = await setClueHandleApi(param)
          if(res.code==1000){
            this.$message.success(res.message)
          }else{
            this.$message.error(res.message)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

回填内容(直接请求接口,赋值form表单的变量值)

async getClueInfo(clue_id){
      const res = await getClueInfoApi({clue_id: clue_id})
      if(res.code==1000){
      	// 回填数据 所有字段形式统一,单独赋值或对象统一赋值
      	//1 单独赋值
        this.form.advert_id = res.data.advert_id
        this.form.title = res.data.title
        this.form.collect_time = moment(res.data.collect_time,'YYYY-MM-DD HH:mm:ss')
        this.form.category_id = [res.data.category_pid,res.data.category_id]
        // 若是后端返回字符串日期格式 需要moment转换一下
        this.form.range_time = [moment("2023-11-20"),[moment("2023-12-30")]]
		//2 对象赋值
		this.form = {
 			advert_id: '',
 			title:'',
 			collect_time: moment(res.data.collect_time,'YYYY-MM-DD HH:mm:ss'),
 			category_id: [res.data.category_pid,res.data.category_id],
 			range_time: [moment("2023-11-20"),[moment("2023-12-30")]]
 		}
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/91523
推荐阅读
相关标签
  

闽ICP备14008679号