uni-forms-item.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <template>
  2. <view class="uni-forms-item"
  3. :class="['is-direction-' + localLabelPos ,border?'uni-forms-item--border':'' ,border && isFirstBorder?'is-first-border':'']">
  4. <slot name="label">
  5. <view class="uni-forms-item__label" :class="{'no-label':!label && !required}"
  6. :style="{width:localLabelWidth,justifyContent: localLabelAlign}">
  7. <text v-if="required" class="is-required">*</text>
  8. <text :style="{fontSize:labelFontSize+'px'}">{{label}}</text>
  9. </view>
  10. </slot>
  11. <!-- #ifndef APP-NVUE -->
  12. <view class="uni-forms-item__content">
  13. <slot></slot>
  14. <view class="uni-forms-item__error" :class="{'msg--active':msg}">
  15. <text>{{msg}}</text>
  16. </view>
  17. </view>
  18. <!-- #endif -->
  19. <!-- #ifdef APP-NVUE -->
  20. <view class="uni-forms-item__nuve-content">
  21. <view class="uni-forms-item__content">
  22. <slot></slot>
  23. </view>
  24. <view class="uni-forms-item__error" :class="{'msg--active':msg}">
  25. <text class="error-text">{{msg}}</text>
  26. </view>
  27. </view>
  28. <!-- #endif -->
  29. </view>
  30. </template>
  31. <script>
  32. /**
  33. * uni-fomrs-item 表单子组件
  34. * @description uni-fomrs-item 表单子组件,提供了基础布局已经校验能力
  35. * @tutorial https://ext.dcloud.net.cn/plugin?id=2773
  36. * @property {Boolean} required 是否必填,左边显示红色"*"号
  37. * @property {String } label 输入框左边的文字提示
  38. * @property {Number } labelWidth label的宽度,单位px(默认70)
  39. * @property {String } labelAlign = [left|center|right] label的文字对齐方式(默认left)
  40. * @value left label 左侧显示
  41. * @value center label 居中
  42. * @value right label 右侧对齐
  43. * @property {String } errorMessage 显示的错误提示内容,如果为空字符串或者false,则不显示错误信息
  44. * @property {String } name 表单域的属性名,在使用校验规则时必填
  45. * @property {String } leftIcon 【1.4.0废弃】label左边的图标,限 uni-ui 的图标名称
  46. * @property {String } iconColor 【1.4.0废弃】左边通过icon配置的图标的颜色(默认#606266)
  47. * @property {String} validateTrigger = [bind|submit|blur] 【1.4.0废弃】校验触发器方式 默认 submit
  48. * @value bind 发生变化时触发
  49. * @value submit 提交时触发
  50. * @value blur 失去焦点触发
  51. * @property {String } labelPosition = [top|left] 【1.4.0废弃】label的文字的位置(默认left)
  52. * @value top 顶部显示 label
  53. * @value left 左侧显示 label
  54. */
  55. export default {
  56. name: 'uniFormsItem',
  57. options: {
  58. // #ifdef MP-TOUTIAO
  59. virtualHost: false,
  60. // #endif
  61. // #ifndef MP-TOUTIAO
  62. virtualHost: true
  63. // #endif
  64. },
  65. provide() {
  66. return {
  67. uniFormItem: this
  68. }
  69. },
  70. inject: {
  71. form: {
  72. from: 'uniForm',
  73. default: null
  74. },
  75. },
  76. props: {
  77. // 表单校验规则
  78. rules: {
  79. type: Array,
  80. default () {
  81. return null;
  82. }
  83. },
  84. // 表单域的属性名,在使用校验规则时必填
  85. name: {
  86. type: [String, Array],
  87. default: ''
  88. },
  89. required: {
  90. type: Boolean,
  91. default: false
  92. },
  93. label: {
  94. type: String,
  95. default: ''
  96. },
  97. // label的宽度
  98. labelWidth: {
  99. type: [String, Number],
  100. default: ''
  101. },
  102. // label 居中方式,默认 left 取值 left/center/right
  103. labelAlign: {
  104. type: String,
  105. default: ''
  106. },
  107. labelFontSize:{
  108. type: Number,
  109. default:15
  110. },
  111. // 强制显示错误信息
  112. errorMessage: {
  113. type: [String, Boolean],
  114. default: ''
  115. },
  116. // 1.4.0 弃用,统一使用 form 的校验时机
  117. // validateTrigger: {
  118. // type: String,
  119. // default: ''
  120. // },
  121. // 1.4.0 弃用,统一使用 form 的label 位置
  122. // labelPosition: {
  123. // type: String,
  124. // default: ''
  125. // },
  126. // 1.4.0 以下属性已经废弃,请使用 #label 插槽代替
  127. leftIcon: String,
  128. iconColor: {
  129. type: String,
  130. default: '#606266'
  131. },
  132. },
  133. data() {
  134. return {
  135. errMsg: '',
  136. userRules: null,
  137. localLabelAlign: 'left',
  138. localLabelWidth: '70px',
  139. localLabelPos: 'left',
  140. border: false,
  141. isFirstBorder: false,
  142. };
  143. },
  144. computed: {
  145. // 处理错误信息
  146. msg() {
  147. return this.errorMessage || this.errMsg;
  148. }
  149. },
  150. watch: {
  151. // 规则发生变化通知子组件更新
  152. 'form.formRules'(val) {
  153. // TODO 处理头条vue3 watch不生效的问题
  154. // #ifndef MP-TOUTIAO
  155. this.init()
  156. // #endif
  157. },
  158. 'form.labelWidth'(val) {
  159. // 宽度
  160. this.localLabelWidth = this._labelWidthUnit(val)
  161. },
  162. 'form.labelPosition'(val) {
  163. // 标签位置
  164. this.localLabelPos = this._labelPosition()
  165. },
  166. 'form.labelAlign'(val) {
  167. }
  168. },
  169. created() {
  170. this.init(true)
  171. if (this.name && this.form) {
  172. // TODO 处理头条vue3 watch不生效的问题
  173. // #ifdef MP-TOUTIAO
  174. this.$watch('form.formRules', () => {
  175. this.init()
  176. })
  177. // #endif
  178. // 监听变化
  179. this.$watch(
  180. () => {
  181. const val = this.form._getDataValue(this.name, this.form.localData)
  182. return val
  183. },
  184. (value, oldVal) => {
  185. const isEqual = this.form._isEqual(value, oldVal)
  186. // 简单判断前后值的变化,只有发生变化才会发生校验
  187. // TODO 如果 oldVal = undefined ,那么大概率是源数据里没有值导致 ,这个情况不哦校验 ,可能不严谨 ,需要在做观察
  188. // fix by mehaotian 暂时取消 && oldVal !== undefined ,如果formData 中不存在,可能会不校验
  189. if (!isEqual) {
  190. const val = this.itemSetValue(value)
  191. this.onFieldChange(val, false)
  192. }
  193. }, {
  194. immediate: false
  195. }
  196. );
  197. }
  198. },
  199. // #ifndef VUE3
  200. destroyed() {
  201. if (this.__isUnmounted) return
  202. this.unInit()
  203. },
  204. // #endif
  205. // #ifdef VUE3
  206. unmounted() {
  207. this.__isUnmounted = true
  208. this.unInit()
  209. },
  210. // #endif
  211. methods: {
  212. /**
  213. * 外部调用方法
  214. * 设置规则 ,主要用于小程序自定义检验规则
  215. * @param {Array} rules 规则源数据
  216. */
  217. setRules(rules = null) {
  218. this.userRules = rules
  219. this.init(false)
  220. },
  221. // 兼容老版本表单组件
  222. setValue() {
  223. // console.log('setValue 方法已经弃用,请使用最新版本的 uni-forms 表单组件以及其他关联组件。');
  224. },
  225. /**
  226. * 外部调用方法
  227. * 校验数据
  228. * @param {any} value 需要校验的数据
  229. * @param {boolean} 是否立即校验
  230. * @return {Array|null} 校验内容
  231. */
  232. async onFieldChange(value, formtrigger = true) {
  233. const {
  234. formData,
  235. localData,
  236. errShowType,
  237. validateCheck,
  238. validateTrigger,
  239. _isRequiredField,
  240. _realName
  241. } = this.form
  242. const name = _realName(this.name)
  243. if (!value) {
  244. value = this.form.formData[name]
  245. }
  246. // fixd by mehaotian 不在校验前清空信息,解决闪屏的问题
  247. // this.errMsg = '';
  248. // fix by mehaotian 解决没有检验规则的情况下,抛出错误的问题
  249. const ruleLen = this.itemRules.rules && this.itemRules.rules.length
  250. if (!this.validator || !ruleLen || ruleLen === 0) return;
  251. // 检验时机
  252. // let trigger = this.isTrigger(this.itemRules.validateTrigger, this.validateTrigger, validateTrigger);
  253. const isRequiredField = _isRequiredField(this.itemRules.rules || []);
  254. let result = null;
  255. // 只有等于 bind 时 ,才能开启时实校验
  256. if (validateTrigger === 'bind' || formtrigger) {
  257. // 校验当前表单项
  258. result = await this.validator.validateUpdate({
  259. [name]: value
  260. },
  261. formData
  262. );
  263. // 判断是否必填,非必填,不填不校验,填写才校验 ,暂时只处理 undefined 和空的情况
  264. if (!isRequiredField && (value === undefined || value === '')) {
  265. result = null;
  266. }
  267. // 判断错误信息显示类型
  268. if (result && result.errorMessage) {
  269. if (errShowType === 'undertext') {
  270. // 获取错误信息
  271. this.errMsg = !result ? '' : result.errorMessage;
  272. }
  273. if (errShowType === 'toast') {
  274. uni.showToast({
  275. title: result.errorMessage || '校验错误',
  276. icon: 'none'
  277. });
  278. }
  279. if (errShowType === 'modal') {
  280. uni.showModal({
  281. title: '提示',
  282. content: result.errorMessage || '校验错误'
  283. });
  284. }
  285. } else {
  286. this.errMsg = ''
  287. }
  288. // 通知 form 组件更新事件
  289. validateCheck(result ? result : null)
  290. } else {
  291. this.errMsg = ''
  292. }
  293. return result ? result : null;
  294. },
  295. /**
  296. * 初始组件数据
  297. */
  298. init(type = false) {
  299. const {
  300. validator,
  301. formRules,
  302. childrens,
  303. formData,
  304. localData,
  305. _realName,
  306. labelWidth,
  307. _getDataValue,
  308. _setDataValue
  309. } = this.form || {}
  310. // 对齐方式
  311. this.localLabelAlign = this._justifyContent()
  312. // 宽度
  313. this.localLabelWidth = this._labelWidthUnit(labelWidth)
  314. // 标签位置
  315. this.localLabelPos = this._labelPosition()
  316. // 将需要校验的子组件加入form 队列
  317. this.form && type && childrens.push(this)
  318. if (!validator || !formRules) return
  319. // 判断第一个 item
  320. if (!this.form.isFirstBorder) {
  321. this.form.isFirstBorder = true;
  322. this.isFirstBorder = true;
  323. }
  324. // 判断 group 里的第一个 item
  325. if (this.group) {
  326. if (!this.group.isFirstBorder) {
  327. this.group.isFirstBorder = true;
  328. this.isFirstBorder = true;
  329. }
  330. }
  331. this.border = this.form.border;
  332. // 获取子域的真实名称
  333. const name = _realName(this.name)
  334. const itemRule = this.userRules || this.rules
  335. if (typeof formRules === 'object' && itemRule) {
  336. // 子规则替换父规则
  337. formRules[name] = {
  338. rules: itemRule
  339. }
  340. validator.updateSchema(formRules);
  341. }
  342. // 注册校验规则
  343. const itemRules = formRules[name] || {}
  344. this.itemRules = itemRules
  345. // 注册校验函数
  346. this.validator = validator
  347. // 默认值赋予
  348. this.itemSetValue(_getDataValue(this.name, localData))
  349. },
  350. unInit() {
  351. if (this.form) {
  352. const {
  353. childrens,
  354. formData,
  355. _realName
  356. } = this.form
  357. childrens.forEach((item, index) => {
  358. if (item === this) {
  359. this.form.childrens.splice(index, 1)
  360. delete formData[_realName(item.name)]
  361. }
  362. })
  363. }
  364. },
  365. // 设置item 的值
  366. itemSetValue(value) {
  367. const name = this.form._realName(this.name)
  368. const rules = this.itemRules.rules || []
  369. const val = this.form._getValue(name, value, rules)
  370. this.form._setDataValue(name, this.form.formData, val)
  371. return val
  372. },
  373. /**
  374. * 移除该表单项的校验结果
  375. */
  376. clearValidate() {
  377. this.errMsg = '';
  378. },
  379. // 是否显示星号
  380. _isRequired() {
  381. // TODO 不根据规则显示 星号,考虑后续兼容
  382. // if (this.form) {
  383. // if (this.form._isRequiredField(this.itemRules.rules || []) && this.required) {
  384. // return true
  385. // }
  386. // return false
  387. // }
  388. return this.required
  389. },
  390. // 处理对齐方式
  391. _justifyContent() {
  392. if (this.form) {
  393. const {
  394. labelAlign
  395. } = this.form
  396. let labelAli = this.labelAlign ? this.labelAlign : labelAlign;
  397. if (labelAli === 'left') return 'flex-start';
  398. if (labelAli === 'center') return 'center';
  399. if (labelAli === 'right') return 'flex-end';
  400. }
  401. return 'flex-start';
  402. },
  403. // 处理 label宽度单位 ,继承父元素的值
  404. _labelWidthUnit(labelWidth) {
  405. // if (this.form) {
  406. // const {
  407. // labelWidth
  408. // } = this.form
  409. return this.num2px(this.labelWidth ? this.labelWidth : (labelWidth || (this.label ? 70 : 'auto')))
  410. // }
  411. // return '70px'
  412. },
  413. // 处理 label 位置
  414. _labelPosition() {
  415. if (this.form) return this.form.labelPosition || 'left'
  416. return 'left'
  417. },
  418. /**
  419. * 触发时机
  420. * @param {Object} rule 当前规则内时机
  421. * @param {Object} itemRlue 当前组件时机
  422. * @param {Object} parentRule 父组件时机
  423. */
  424. isTrigger(rule, itemRlue, parentRule) {
  425. // bind submit
  426. if (rule === 'submit' || !rule) {
  427. if (rule === undefined) {
  428. if (itemRlue !== 'bind') {
  429. if (!itemRlue) {
  430. return parentRule === '' ? 'bind' : 'submit';
  431. }
  432. return 'submit';
  433. }
  434. return 'bind';
  435. }
  436. return 'submit';
  437. }
  438. return 'bind';
  439. },
  440. num2px(num) {
  441. if (typeof num === 'number') {
  442. return `${num}px`
  443. }
  444. return num
  445. }
  446. }
  447. };
  448. </script>
  449. <style lang="scss">
  450. .uni-forms-item {
  451. position: relative;
  452. display: flex;
  453. /* #ifdef APP-NVUE */
  454. // 在 nvue 中,使用 margin-bottom error 信息会被隐藏
  455. padding-bottom: 22px;
  456. /* #endif */
  457. /* #ifndef APP-NVUE */
  458. margin-bottom: 22px;
  459. /* #endif */
  460. flex-direction: row;
  461. &__label {
  462. display: flex;
  463. flex-direction: row;
  464. align-items: center;
  465. text-align: left;
  466. font-size: 14px;
  467. color: #606266;
  468. height: 36px;
  469. padding: 0 12px 0 0;
  470. /* #ifndef APP-NVUE */
  471. vertical-align: middle;
  472. flex-shrink: 0;
  473. /* #endif */
  474. /* #ifndef APP-NVUE */
  475. box-sizing: border-box;
  476. /* #endif */
  477. &.no-label {
  478. padding: 0;
  479. }
  480. }
  481. &__content {
  482. /* #ifndef MP-TOUTIAO */
  483. // display: flex;
  484. // align-items: center;
  485. /* #endif */
  486. position: relative;
  487. font-size: 14px;
  488. flex: 1;
  489. /* #ifndef APP-NVUE */
  490. box-sizing: border-box;
  491. /* #endif */
  492. flex-direction: row;
  493. /* #ifndef APP || H5 || MP-WEIXIN || APP-NVUE */
  494. // TODO 因为小程序平台会多一层标签节点 ,所以需要在多余节点继承当前样式
  495. &>uni-easyinput,
  496. &>uni-data-picker {
  497. width: 100%;
  498. }
  499. /* #endif */
  500. }
  501. & .uni-forms-item__nuve-content {
  502. display: flex;
  503. flex-direction: column;
  504. flex: 1;
  505. }
  506. &__error {
  507. color: #f56c6c;
  508. font-size: 12px;
  509. line-height: 1;
  510. padding-top: 4px;
  511. position: absolute;
  512. /* #ifndef APP-NVUE */
  513. top: 100%;
  514. left: 0;
  515. transition: transform 0.3s;
  516. transform: translateY(-100%);
  517. /* #endif */
  518. /* #ifdef APP-NVUE */
  519. bottom: 5px;
  520. /* #endif */
  521. opacity: 0;
  522. .error-text {
  523. // 只有 nvue 下这个样式才生效
  524. color: #f56c6c;
  525. font-size: 12px;
  526. }
  527. &.msg--active {
  528. opacity: 1;
  529. transform: translateY(0%);
  530. }
  531. }
  532. // 位置修饰样式
  533. &.is-direction-left {
  534. flex-direction: row;
  535. }
  536. &.is-direction-top {
  537. flex-direction: column;
  538. .uni-forms-item__label {
  539. padding: 0 0 8px;
  540. line-height: 1.5715;
  541. text-align: left;
  542. /* #ifndef APP-NVUE */
  543. white-space: initial;
  544. /* #endif */
  545. }
  546. }
  547. .is-required {
  548. // color: $uni-color-error;
  549. color: #dd524d;
  550. font-weight: bold;
  551. }
  552. }
  553. .uni-forms-item--border {
  554. margin-bottom: 0;
  555. padding: 10px 0;
  556. // padding-bottom: 0;
  557. border-top: 1px #eee solid;
  558. /* #ifndef APP-NVUE */
  559. .uni-forms-item__content {
  560. flex-direction: column;
  561. justify-content: flex-start;
  562. align-items: flex-start;
  563. .uni-forms-item__error {
  564. position: relative;
  565. top: 5px;
  566. left: 0;
  567. padding-top: 0;
  568. }
  569. }
  570. /* #endif */
  571. /* #ifdef APP-NVUE */
  572. display: flex;
  573. flex-direction: column;
  574. .uni-forms-item__error {
  575. position: relative;
  576. top: 0px;
  577. left: 0;
  578. padding-top: 0;
  579. margin-top: 5px;
  580. }
  581. /* #endif */
  582. }
  583. .is-first-border {
  584. /* #ifndef APP-NVUE */
  585. border: none;
  586. /* #endif */
  587. /* #ifdef APP-NVUE */
  588. border-width: 0;
  589. /* #endif */
  590. }
  591. </style>