uni-forms-item.vue 16 KB

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