uni-forms-item.vue 15 KB

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