uni-forms-item.vue 15 KB

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