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 && !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. if (this.form) {
  376. return this.required || this.form._isRequiredField(this.itemRules.rules || [])
  377. }
  378. return this.required
  379. },
  380. // 处理对齐方式
  381. _justifyContent() {
  382. if (this.form) {
  383. const {
  384. labelAlign
  385. } = this.form
  386. let labelAli = this.labelAlign ? this.labelAlign : labelAlign;
  387. if (labelAli === 'left') return 'flex-start';
  388. if (labelAli === 'center') return 'center';
  389. if (labelAli === 'right') return 'flex-end';
  390. }
  391. return 'flex-start';
  392. },
  393. // 处理 label宽度单位 ,继承父元素的值
  394. _labelWidthUnit(labelWidth) {
  395. // if (this.form) {
  396. // const {
  397. // labelWidth
  398. // } = this.form
  399. return this.num2px(this.labelWidth ? this.labelWidth : (labelWidth || (this.label ? 65 : 'auto')))
  400. // }
  401. // return '65px'
  402. },
  403. // 处理 label 位置
  404. _labelPosition() {
  405. if (this.form) return this.form.labelPosition || 'left'
  406. return 'left'
  407. },
  408. /**
  409. * 触发时机
  410. * @param {Object} rule 当前规则内时机
  411. * @param {Object} itemRlue 当前组件时机
  412. * @param {Object} parentRule 父组件时机
  413. */
  414. isTrigger(rule, itemRlue, parentRule) {
  415. // bind submit
  416. if (rule === 'submit' || !rule) {
  417. if (rule === undefined) {
  418. if (itemRlue !== 'bind') {
  419. if (!itemRlue) {
  420. return parentRule === '' ? 'bind' : 'submit';
  421. }
  422. return 'submit';
  423. }
  424. return 'bind';
  425. }
  426. return 'submit';
  427. }
  428. return 'bind';
  429. },
  430. num2px(num) {
  431. if (typeof num === 'number') {
  432. return `${num}px`
  433. }
  434. return num
  435. }
  436. }
  437. };
  438. </script>
  439. <style lang="scss">
  440. .uni-forms-item {
  441. position: relative;
  442. display: flex;
  443. /* #ifdef APP-NVUE */
  444. // 在 nvue 中,使用 margin-bottom error 信息会被隐藏
  445. padding-bottom: 22px;
  446. /* #endif */
  447. /* #ifndef APP-NVUE */
  448. margin-bottom: 22px;
  449. /* #endif */
  450. flex-direction: row;
  451. &__label {
  452. display: flex;
  453. flex-direction: row;
  454. align-items: center;
  455. text-align: left;
  456. font-size: 14px;
  457. color: #606266;
  458. height: 36px;
  459. padding: 0 12px 0 0;
  460. /* #ifndef APP-NVUE */
  461. vertical-align: middle;
  462. flex-shrink: 0;
  463. /* #endif */
  464. /* #ifndef APP-NVUE */
  465. box-sizing: border-box;
  466. /* #endif */
  467. &.no-label {
  468. padding: 0;
  469. }
  470. }
  471. &__content {
  472. /* #ifndef MP-TOUTIAO */
  473. // display: flex;
  474. // align-items: center;
  475. /* #endif */
  476. position: relative;
  477. font-size: 14px;
  478. flex: 1;
  479. /* #ifndef APP-NVUE */
  480. box-sizing: border-box;
  481. /* #endif */
  482. flex-direction: row;
  483. /* #ifndef APP || H5 || MP-WEIXIN || APP-NVUE */
  484. // TODO 因为小程序平台会多一层标签节点 ,所以需要在多余节点继承当前样式
  485. &>uni-easyinput,
  486. &>uni-data-picker {
  487. width: 100%;
  488. }
  489. /* #endif */
  490. }
  491. & .uni-forms-item__nuve-content {
  492. display: flex;
  493. flex-direction: column;
  494. flex: 1;
  495. }
  496. &__error {
  497. color: #f56c6c;
  498. font-size: 12px;
  499. line-height: 1;
  500. padding-top: 4px;
  501. position: absolute;
  502. /* #ifndef APP-NVUE */
  503. top: 100%;
  504. left: 0;
  505. transition: transform 0.3s;
  506. transform: translateY(-100%);
  507. /* #endif */
  508. /* #ifdef APP-NVUE */
  509. bottom: 5px;
  510. /* #endif */
  511. opacity: 0;
  512. .error-text {
  513. // 只有 nvue 下这个样式才生效
  514. color: #f56c6c;
  515. font-size: 12px;
  516. }
  517. &.msg--active {
  518. opacity: 1;
  519. transform: translateY(0%);
  520. }
  521. }
  522. // 位置修饰样式
  523. &.is-direction-left {
  524. flex-direction: row;
  525. }
  526. &.is-direction-top {
  527. flex-direction: column;
  528. .uni-forms-item__label {
  529. padding: 0 0 8px;
  530. line-height: 1.5715;
  531. text-align: left;
  532. /* #ifndef APP-NVUE */
  533. white-space: initial;
  534. /* #endif */
  535. }
  536. }
  537. .is-required {
  538. // color: $uni-color-error;
  539. color: #dd524d;
  540. font-weight: bold;
  541. }
  542. }
  543. .uni-forms-item--border {
  544. margin-bottom: 0;
  545. padding: 10px 0;
  546. // padding-bottom: 0;
  547. border-top: 1px #eee solid;
  548. /* #ifndef APP-NVUE */
  549. .uni-forms-item__content {
  550. flex-direction: column;
  551. justify-content: flex-start;
  552. align-items: flex-start;
  553. .uni-forms-item__error {
  554. position: relative;
  555. top: 5px;
  556. left: 0;
  557. padding-top: 0;
  558. }
  559. }
  560. /* #endif */
  561. /* #ifdef APP-NVUE */
  562. display: flex;
  563. flex-direction: column;
  564. .uni-forms-item__error {
  565. position: relative;
  566. top: 0px;
  567. left: 0;
  568. padding-top: 0;
  569. margin-top: 5px;
  570. }
  571. /* #endif */
  572. }
  573. .is-first-border {
  574. /* #ifndef APP-NVUE */
  575. border: none;
  576. /* #endif */
  577. /* #ifdef APP-NVUE */
  578. border-width: 0;
  579. /* #endif */
  580. }
  581. </style>