uni-forms-item.vue 15 KB

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