uni-forms-item.vue 15 KB

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