记录一下AntDesignVue开发过程中遇到的问题

目的:记录一下自己工作过程中遇到的 Ant Design Vue 开发问题

文章目录


Ant Design Vue 开发问题


async和await让异步编程更简单

https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Async_await


1、antdv中table组件 scopedSlots 和 ellipsis 属性一起使用,悬浮框失效问题

https://blog.csdn.net/qq_42067121/article/details/118080332
	加 title 即可解决
	<span
        slot="kskm"
        slot-scope="text"
      >
        <span :title="kskmtest(text)">{{ kskmtest(text) }}</span>
    </span>

2、antdv修改调用的后端地址

修改.env.development文件中的 VUE_APP_BASE_API_DJRD = ‘/djrd-qyd-core-hcx/api/v1’(自己的后端地址)


3、Java修改application名称和IP地址

bootstrap.yml文件中修改
		应用名称:spring:
					application:
						name: djrd-qyd-core-hcx(自己的应用名称)
		IP地址:eureka:
					instance:
						ip-address: 192.168.47.161(自己的IP地址,不要写localhost/127.0.0.1

4、antdv调用后端接口文件

放在src/api/interfaces/xxx.js 并且需要在src/api/index.js文件中声明


5、antdv路由文件

放在src/router/module/xxx.js src/router/index.js文件中声明


6、antdv前端页面文件

放在src/views/xxx.vue


7、s-table的columns属性值可以动态新增列并控制显示/不显示

columns () {
		const newColums = []
		//判断是否新增
		if (this.pjkm.indexOf('01') !== -1) {
			//新增的列
			newColums.push({
				title: '理论成绩',
				dataIndex: 'llcj',
				width: 60,
				scopedSlots: { customRender: 'llcj' }
			})
		}
		return[
			{
				title: '序号',
				scopedSlots: { customRender: 'serial' },
				width: 50
			},
			{
				title: '姓名',
				ellipsis: true,
				dataIndex: 'bgc023',
				width: 60
			},
			//显示新增的列
			...newColums,
			{
				title: '准考证号',
				ellipsis: true,
				dataIndex: 'zkzh',
				width: 80
			},
		]
	}

8、页面搜索框和选择框对齐问题

目前对齐方式为:左边的框左对齐(style="float:left")
					中间的框居中对齐(style="text-align: center")
					右边的框右对齐(style="float:right"

9、s-table加横向滚动条

:scroll="{ x: 1200 }"

10、s-table使用插槽列表中的文字不对齐问题

//使用插槽
		scopedSlots: { customRender: 'kskm' }
		//插槽
		<span
			slot="kskm"
			slot-scope="text"
		>
			//不要使用<p>标签显示数据即可
			//<p :title="kskmtest(text)">{{ kskmtest(text) }}</p>
			<span :title="kskmtest(text)">{{ kskmtest(text) }}</span>
		</span>

11、vue 动态表单 点击增加添加输入框,删除根据下标删除

参考文章链接


12、span标签字体加粗

<span style="font-weight:bold">修改成绩原因</span>

13、span标签字体大小

<span style="font-size:15px">成绩</span>

14、居中对齐

<a-col :span="8" style="text-align: center">

15、前端发送PUT请求使用封装好的 Http.putUrlencoded(如果用的requestBody还是要用Http.request.put那个)

updateZdUserStatus(params) {
   return Http.putUrlencoded(
     baseUrl + '/updateZdUserStatus',
     params
   ).then(({ data }) => data)
}

16、刷新页面

this.$refs['queryForm'].resetFields()
this.$refs['kwjhTable'].refresh(true)

17、表单校验textarea必填项

<a-form-model ref="kscjbjQueryForm" :rules="rules" :model="kscjbjData">
  <a-row>
	<a-col>
	  <a-form-model-item prop="changeAchievementReason" label="修改成绩原因" style="font-weight:bold">
		<a-textarea
		  v-model="kscjbjData.changeAchievementReason"
		  placeholder="请输入修改成绩原因"
		  :auto-size="{ minRows: 4, maxRows: 8 }"
		/>
	  </a-form-model-item>
	</a-col>
  </a-row>
</a-form-model>

18、获取路由push传递的值

this.$route.query.practiceId || ''

19、声明属性

props: {
    busId: {
      type: String,
      default: ''
    },
    initType: {
      type: String,
      default: ''
    }
  }

20、使用插槽的同时省略列表内容

<a-popover
        slot="contentPop"
        slot-scope="text, record"
      >
        <template slot="content">
          {{ getContent(record.questionName) }}
        </template>
        {{ getContent(record.questionName).length > 16?getContent(record.questionName).substr(0,16) + '...' : getContent(record.questionName) }}
      </a-popover>

21、边框贴着右边
和 style=“margin-right: 0px” 一起使用

<div style="float:right">
            <a-form-model-item
              label="练习时间"
              prop="name"
              :colon="false"
              style="margin-right: 0px"
            >
              <a-range-picker
                v-model="yxrq"
                style="width: 200px;"
                type="date"
                :format="dateFormat"
                :value-format="dateFormat"
                @change="(date, dateString) => { handleDateChange('yxrq', date, dateString) }"
              />
            </a-form-model-item>
          </div>

22、已封装好的方法,校验身份证格式港澳证件号码格式

idCardCheck


23、table固定列

fixed: 'left',
ellipsis: true,	//省略

fixed: 'right',
ellipsis: true,	//省略

24、调用其他页面的方法,方式一(页面1要引入页面2作为组件)

//被调用的是异步方法
	handleOk () {
      const self = this
      self.confirmLoading = true
      self.$refs['stkEditModal'].handleSave().then(() => {	//这句代码调用了其他页面2的handleSave方法,handleSave是异步方法才需要.then和.catch
        self.showModal = false
        self.handleSearch()
      }).catch(err => {
        self.$message.error(err.errmsg)
      }).finally(() => {
        self.confirmLoading = false
      })
    },
	//被调用的是普通方法
	const self = this
    const reslut = self.$refs['ybmWaitingQueue'].toggleCollapsed()
    console.log('reslut', reslut)

25、调用其他页面的方法,方式二(页面2要引入页面1作为组件)

页面1(子组件):
		lxtksjk-type-tree.vue有一个方法
			deleteTreeNode (treeData) {
			console.log('删除分类', treeData, this.dataType)
			api.lxtk.deleteTreeNode({
				id: treeData.key,
				type: this.dataType
			}).then(res => {
				console.log('删除树分类', res)
				this.$message.success('删除成功')
				this.$emit('handleDelete')			//这句代码调用了页面2的handleDelete方法
				this.queryTreeNode()
			}).catch(err => {
				console.error(err)
				this.$message.error(err.errmsg)
			})
			},
	页面2(父组件):
		lxtk-list.vue引用了页面1作为组件
			<a-col :span="5">
				<StklbTree
				style="height: 100%;"
				data-type="question-library"
				@handleSelect="handleSelectTree"
				@handleDelete="handleDeleteTreeNode"	//这句代码表示被引用的子组件可以调用父组件的handleDeleteTreeNode方法
				/>
			</a-col>

26、弹窗调用接口

const self = this
      this.$confirm({
        title: '是否确认将所选记录审核通过,并提交至区审核环节?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const id = [self.cdb341]
          api.ljyjt_qsh.ljyjt_qsh_qshtg({
            cdb293: self.form.cdb293,
            shsm: self.cdb304,
            lshList: id
          }).then((res) => {
            self.$message.success('提交成功')
            self.cdb304 = ''
            self.getData()
          })
            .catch((err) => {
              self.$message.error(err)
            }).finally(() => {
              self.searchLoading = false
            })
        }
      })

27、列表实现单选功能

//第一步
<sinogear-table
      :columns="columns"
      :row-selection="ljyRowSelection"	//自定义单选功能
      :data-source="data"
      :dicts="dicts"
      :scroll="{x:true}"
      :loading="searchLoading"
      :pagination="defaultPage"
      bordered
      @change="handlePaginationChange"
    >
      <span
        slot="num"
        slot-scope="item"
      >{{ item.num+1 }}</span>
      <span
        slot="cce62p"
        slot-scope="item"
      >
        <span
          v-if="item==='1'"
          style="display:inline-block; width:20px;height:20px;background:red;border-radius:20px"
        >
          <span style="visibility:hidden">1</span>
        </span>
      </span>
    </sinogear-table>
	//第二步
	return {
      selectedLjyRowKeys: [],
      selectedLjyRow: [],
    }
	//第三步
  computed: {
    ljyRowSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.selectedLjyRowKeys,
        onChange: (selectedRowKeys, selectedRow) => {
          console.log(selectedRowKeys, selectedRow[0].cdb341)
          this.selectedLjyRowKeys = selectedRowKeys
          this.selectedLjyRow = selectedRow
          this.cdb341 = selectedRow[0].cdb341
        }
      }
    }
  },

28、弹框同步调用2个方法

async submitHandle() {
      const self = this
      const userInfo = auth.getUserInfo()
      if (userInfo.orgCode.length !== 6 && userInfo.orgCode.length !== 8) {
        self.$message.error('非街/区级用户没有权限')
        return
      }
      await self.$refs.formRef.validate((valid) => {
        if (valid) {
          self.$confirm({
            content: '是否将当前数据保存并上报?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
              self.$refs.formRef.validate(async(valid) => {
                if (valid) {
                  self.form.ccb489 = self.userInFo.id
                  self.form.ccb491 = self.userInFo.orgCodeOld
                  self.form.ccb490 = moment().format('YYYY-MM-DD')
                  try {
                    const result = await api.ljyjt_xxtb.ljyjt_xxtb_bctbxx({ ...self.form })
                    if (result) {
                      api.ljyjt_xxtb.ljyjt_xxtb_tjtbxx({
                        lshList: self.$route.query.cdb341
                      }).then((res) => {
                        self.$message.success('提交成功')
                        self.$router.back()
                      }).catch((err) => {
                        self.$message.error(err)
                      }).finally(() => {
                        self.searchLoading = false
                      })
                    }
                  } catch (error) {
                    self.$message.error(error)
                  }
                }
              })
            },
            onCancel() {}
          })
        }
      })
    },

29、成对的输入框

参考ant design vue组件Descriptions 列表描述


30、通过设置边缘距离保持框对齐

style="margin-right: 0px"
style="margin-left:28px"
style="margin-top:5px"
style="margin-bottom:10px"

31、感叹号提示信息

<template>
        <a-popover>
          <template slot="content">
            <span>导出考生名单:仅导出已勾选,并且安排状态为"已安排"的考生</span>
          </template>
          <a-icon type="exclamation-circle" />
        </a-popover>
      </template>

32、对话框不要有任何按钮

<a-modal
      v-model="showExamineeModal"
      title="考生信息"
      width="850px"
      centered
      style="top:20px"
      destroy-on-close
      :footer="null"			//对话框不要有任何按钮
      @cancel="handleCancel"
    >
      <ExamineeModal
        ref="ExamineeModal"
      />
    </a-modal>

33、蓝色竖线

<div class="card-title title-bottom">	//长下划线
      <div class="card-label">
        <div class="block-sec" />
        <span class="card-title-text">
          查询条件
        </span>
      </div>
    </div>

34、赋值

this.$set(this.formData, 'bgb221', val)

35、蓝色温馨提示

<div class="box-tips">
        <a-icon
          style="margin-left:10px;font-size:15px"
          type="exclamation-circle"
          theme="filled"
        />
        温馨提示:选择职业工种变更的考点后,需前往“考点申报”界面,上传“考点申请表”。
      </div>

36、css自定义颜色

.colorOne{
  color: rgba(245, 154, 35);
}

37、路由跳转

this.$router.push({
          path: 'baxq',
          query: {
            initType: 'edit'
          }
        })

38、loadData写死数据

return new Promise((resolve, reject) => {
        resolve({
          pageNo: 1,
          totalCount: 1,
          data: [{zymc: '保育员', gzmc: '无', dj: '一级、二级、三级、四级', bmsj: '2022-11-10-2022-11-15', ybmzt: '启用'}]
        })
      })

39、返回按钮后的长分割线

<div class="card-title title-bottom" style="border-bottom: 1px solid #e8e8e8;">
...
</div>

40、自定义日期选择器按钮

<a-col :span="8">
            <a-form-model-item
              label="报名日期"
              prop="tjrq"
              :colon="false"
              style="margin-right: 0px"
            >
              <a-range-picker
                v-model="formData.bmsj"
                style="width: 200px"
                :ranges="{ '今天': [moment(moment().format('YYYY-MM-DD')), moment(moment().format('YYYY-MM-DD')+' 23:59:59')],
                           '近7天': [moment(moment().format('YYYY-MM-DD')).add(-6,'day'), moment(moment().format('YYYY-MM-DD')+' 23:59:59')],
                           '当月': [moment().startOf('month'), moment(moment().format('YYYY-MM-DD')+' 23:59:59')] }"
                :show-time="{defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]}"	//设置用户选择日期时默认的时分秒
                format="YYYY/MM/DD HH:mm:ss"
                @change="onChangeDate"
              />
            </a-form-model-item>
          </a-col>
		  
onChangeDate(dates, dateStrings) {
      console.log('From: ', dates[0], ', to: ', dates[1])
      console.log('From: ', dateStrings[0], ', to: ', dateStrings[1])
    },

41、style样式用对象的方式赋值,可以使用自定义的变量进行动态改变值

//rightWidth是自己定义的变量,可以根据情况改变赋值
//display: 'inline-block' 可以让多个div在同一行显示(前提是多个div的width相加占比不超过100%),不分行
<div :style="{display: 'inline-block',width:rightWidth}">	

42、前端查字典

mounted() {
    this.$svDict
      .getDicts({
        perPage: ['BGE116'],
        perDay: [],
        perWeek: []
      })
      .then((res) => {
        this.dicts = res.perPage
      })
  },

43、使用插槽给列表的标题加感叹号

	{
         // title: '推荐总人数',			//不要标题
         dataIndex: 'recNumber',
         slots: { title: 'recNumber' },	//使用插槽
         width: 80
    },
//定义插槽
<span slot="recNumber">
        推荐总人次
        <template>
          <a-popover>
            <template slot="content">
              <span>提交预报名申请的人次(一个考生可能重复报名多次)</span>
            </template>
            <a-icon type="exclamation-circle" />
          </a-popover>
        </template>
      </span>

44、有序列表、无序列表

<ul> <ol> <li>

45、正则表达式校验字段

rules: {
        bgc026: [
          {
            required: true,
            message: '请填写手机号码',
            trigger: 'blur'
          },
          {
            pattern: /^[1][3-9][0-9]{9}$/,
            message: '请确认您的手机号码填写是否有误',
            trigger: 'blur'
          }
        ]
      }

46、下载文件并将流转为http地址

handleDownland () {
      api.kwjhKsxx.download({
        id: this.fileid
      }).then(res => {
        console.log('------下载附件-------', res)
        this.formData.url = res.url
        const fileNameStr = res.fileType.split('.')
        const fileType = fileNameStr[fileNameStr.length - 1]
        this.formData.fileType = fileType
      }).catch(err => {
        console.error(err)
        this.$message.error(err.errmsg)
      })
    }
	
async download (params) {
    const res = await Http.download(baseUrlFile + `/storage/download`, params)
    const blob = new Blob([res.data], { type: ['image/jpeg', 'application/pdf'] }) // 图片类型 'image/jpeg' pdf类型:application/pdf
    const href = window.URL.createObjectURL(blob)
    const resData = {
      'url': href,	//返回一个http地址
      'fileType': res.headers['content-disposition']	//从这里获取文件名
    }
    return resData
    // window.open(href)  //这里是直接打开一个窗口去预览
  }

47、取消保存按钮插槽

<template slot="footer">
          <a-button @click="handleCancel()">
            取消
          </a-button>
          <a-button
            type="primary"
            @click="save()"
          >保存
          </a-button>
        </template>

48、这个方法可以获取到其他页面返回按钮,返回来的路由

beforeRouteEnter (to, from, next) {
    console.log('返回来的路由', from)
    next(vm => {
      if (from.name === 'ksxx-grbk-all-detail' || from.name === 'addStudent' || from.name === 'ksxx-detail') {
        vm.paneKey = 'tjfs'
      }
    })
  },

49、用插槽手动换行

<a-col :span="8">
            <a-form-model-item class="stress-field" :colon="false">
              <div slot="label" class="stress line-feed">工作人员身份证<br />号码</div>
              <a-input v-model="formData.ksny" allowClear/>
            </a-form-model-item>
          </a-col>
		  
.stress-field ::v-deep .ant-form-item-label {
  label {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .line-feed {
      line-height: 1.5;
    }
  }
}

50、分隔线

<a-divider type="vertical" />

51、返回按钮

handleBack() {
      this.$router.go(-1)
    },

52、限制输入框只能输入整数

<a-input
              v-if="record.editable"
              oninput="value=value.replace(/[^\d]/g,'')"	//正则表达式
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />

53、正整数正则表达式

var numReg = /^\+?[1-9][0-9]*$/;
      var numRe = new RegExp(numReg);
      if (!numRe.test(target.BFB)) {
        this.$message.error("百分比只能输入数字");
        return;
      }

54、监听属性变化

watch: {
    bdz26d() {	//监听bdz26d
      this.getList();	//bdz26d变化就调用方法
    }
  },

55、获取当前季度

boe484End: {
          "01": moment().format("YYYY") + "01",
          "02": moment().format("YYYY") + "01",
          "03": moment().format("YYYY") + "01",
          "04": moment().format("YYYY") + "02",
          "05": moment().format("YYYY") + "02",
          "06": moment().format("YYYY") + "02",
          "07": moment().format("YYYY") + "03",
          "08": moment().format("YYYY") + "03",
          "09": moment().format("YYYY") + "03",
          "10": moment().format("YYYY") + "04",
          "11": moment().format("YYYY") + "04",
          "12": moment().format("YYYY") + "04"
        }[moment().format("MM")]

56、判断是否是字符串

typeof (this.formData.bhc003) === "string" ? '是' : '否'

57、同步关键字

async	await

58、js判断2个日期相差年月

const diff = moment(this.formData.bde325End).diff(moment(this.formData.bde325Begin), "months");
      console.log("年月相差", diff);

59、定义js方法时可以给入参加默认值,调用时可以不传递带有默认值的参数

queryDetailFormOther(busId, bze204 = "") {}	//定义带有默认值的方法,bze204默认为空串
queryDetailFormOther(busId);	//调用时可以不传递带有默认值的参数

60、右下角悬浮返回按钮

<back-off @click="handleBack" bottom="200px"/>

61、用标签渲染列表数据使用单选按钮

single(单选)、multiple(多选)


62、 加上 destroy-on-close属性

可以在关闭时销毁整个对话框,能解决一些问题
比如:点击审核按钮时,点击确定按钮,输入框的必录校验弹出信息“审核信息不能为空”,然后点击取消/关闭按钮,
然后再点击审核按钮,还未点击确定按钮,校验信息就直接出现了,加上destroy-on-close就可以解决这个问题

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值