uni-forms-item.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. if (!isEqual && oldVal !== undefined) {
  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. this.isRequired = this.required
  308. // 将需要校验的子组件加入form 队列
  309. this.form && type && childrens.push(this)
  310. if (!validator || !formRules) return
  311. // 判断第一个 item
  312. if (!this.form.isFirstBorder) {
  313. this.form.isFirstBorder = true;
  314. this.isFirstBorder = true;
  315. }
  316. // 判断 group 里的第一个 item
  317. if (this.group) {
  318. if (!this.group.isFirstBorder) {
  319. this.group.isFirstBorder = true;
  320. this.isFirstBorder = true;
  321. }
  322. }
  323. this.border = this.form.border;
  324. // 获取子域的真实名称
  325. const name = _realName(this.name)
  326. const itemRule = this.userRules || this.rules
  327. if (typeof formRules === 'object' && itemRule) {
  328. // 子规则替换父规则
  329. formRules[name] = {
  330. rules: itemRule
  331. }
  332. validator.updateSchema(formRules);
  333. }
  334. // 注册校验规则
  335. const itemRules = formRules[name] || {}
  336. this.itemRules = itemRules
  337. // 注册校验函数
  338. this.validator = validator
  339. // 默认值赋予
  340. this.itemSetValue(_getDataValue(this.name, localData))
  341. this.isRequired = this._isRequired()
  342. },
  343. unInit() {
  344. if (this.form) {
  345. const {
  346. childrens,
  347. formData,
  348. _realName
  349. } = this.form
  350. childrens.forEach((item, index) => {
  351. if (item === this) {
  352. this.form.childrens.splice(index, 1)
  353. delete formData[_realName(item.name)]
  354. }
  355. })
  356. }
  357. },
  358. // 设置item 的值
  359. itemSetValue(value) {
  360. const name = this.form._realName(this.name)
  361. const rules = this.itemRules.rules || []
  362. const val = this.form._getValue(name, value, rules)
  363. this.form._setDataValue(name, this.form.formData, val)
  364. return val
  365. },
  366. /**
  367. * 移除该表单项的校验结果
  368. */
  369. clearValidate() {
  370. this.errMsg = '';
  371. },
  372. // 是否显示星号
  373. _isRequired() {
  374. if (this.form) {
  375. return this.required || this.form._isRequiredField(this.itemRules.rules || [])
  376. }
  377. return this.required
  378. },
  379. // 处理对齐方式
  380. _justifyContent() {
  381. if (this.form) {
  382. const {
  383. labelAlign
  384. } = this.form
  385. let labelAli = this.labelAlign ? this.labelAlign : labelAlign;
  386. if (labelAli === 'left') return 'flex-start';
  387. if (labelAli === 'center') return 'center';
  388. if (labelAli === 'right') return 'flex-end';
  389. }
  390. return 'flex-start';
  391. },
  392. // 处理 label宽度单位 ,继承父元素的值
  393. _labelWidthUnit(labelWidth) {
  394. // if (this.form) {
  395. // const {
  396. // labelWidth
  397. // } = this.form
  398. return this.num2px(this.labelWidth ? this.labelWidth : (labelWidth || (this.label ? 65 : 'auto')))
  399. // }
  400. // return '65px'
  401. },
  402. // 处理 label 位置
  403. _labelPosition() {
  404. if (this.form) return this.form.labelPosition || 'left'
  405. return 'left'
  406. },
  407. /**
  408. * 触发时机
  409. * @param {Object} rule 当前规则内时机
  410. * @param {Object} itemRlue 当前组件时机
  411. * @param {Object} parentRule 父组件时机
  412. */
  413. isTrigger(rule, itemRlue, parentRule) {
  414. // bind submit
  415. if (rule === 'submit' || !rule) {
  416. if (rule === undefined) {
  417. if (itemRlue !== 'bind') {
  418. if (!itemRlue) {
  419. return parentRule === '' ? 'bind' : 'submit';
  420. }
  421. return 'submit';
  422. }
  423. return 'bind';
  424. }
  425. return 'submit';
  426. }
  427. return 'bind';
  428. },
  429. num2px(num) {
  430. if (typeof num === 'number') {
  431. return `${num}px`
  432. }
  433. return num
  434. }
  435. }
  436. };
  437. </script>
  438. <style lang="scss">
  439. .uni-forms-item {
  440. position: relative;
  441. display: flex;
  442. /* #ifdef APP-NVUE */
  443. // 在 nvue 中,使用 margin-bottom error 信息会被隐藏
  444. padding-bottom: 22px;
  445. /* #endif */
  446. /* #ifndef APP-NVUE */
  447. margin-bottom: 22px;
  448. /* #endif */
  449. flex-direction: row;
  450. &__label {
  451. display: flex;
  452. flex-direction: row;
  453. align-items: center;
  454. text-align: left;
  455. font-size: 14px;
  456. color: #606266;
  457. height: 36px;
  458. padding: 0 12px 0 0;
  459. /* #ifndef APP-NVUE */
  460. vertical-align: middle;
  461. flex-shrink: 0;
  462. /* #endif */
  463. /* #ifndef APP-NVUE */
  464. box-sizing: border-box;
  465. /* #endif */
  466. &.no-label {
  467. padding: 0;
  468. }
  469. }
  470. &__content {
  471. /* #ifndef MP-TOUTIAO */
  472. // display: flex;
  473. // align-items: center;
  474. /* #endif */
  475. position: relative;
  476. font-size: 14px;
  477. flex: 1;
  478. /* #ifndef APP-NVUE */
  479. box-sizing: border-box;
  480. /* #endif */
  481. flex-direction: row;
  482. /* #ifndef APP || H5 || MP-WEIXIN || APP-NVUE */
  483. // TODO 因为小程序平台会多一层标签节点 ,所以需要在多余节点继承当前样式
  484. &>uni-easyinput,
  485. &>uni-data-picker {
  486. width: 100%;
  487. }
  488. /* #endif */
  489. }
  490. & .uni-forms-item__nuve-content {
  491. display: flex;
  492. flex-direction: column;
  493. flex: 1;
  494. }
  495. &__error {
  496. color: #f56c6c;
  497. font-size: 12px;
  498. line-height: 1;
  499. padding-top: 4px;
  500. position: absolute;
  501. /* #ifndef APP-NVUE */
  502. top: 100%;
  503. left: 0;
  504. transition: transform 0.3s;
  505. transform: translateY(-100%);
  506. /* #endif */
  507. /* #ifdef APP-NVUE */
  508. bottom: 5px;
  509. /* #endif */
  510. opacity: 0;
  511. .error-text {
  512. // 只有 nvue 下这个样式才生效
  513. color: #f56c6c;
  514. font-size: 12px;
  515. }
  516. &.msg--active {
  517. opacity: 1;
  518. transform: translateY(0%);
  519. }
  520. }
  521. // 位置修饰样式
  522. &.is-direction-left {
  523. flex-direction: row;
  524. }
  525. &.is-direction-top {
  526. flex-direction: column;
  527. .uni-forms-item__label {
  528. padding: 0 0 8px;
  529. line-height: 1.5715;
  530. text-align: left;
  531. /* #ifndef APP-NVUE */
  532. white-space: initial;
  533. /* #endif */
  534. }
  535. }
  536. .is-required {
  537. // color: $uni-color-error;
  538. color: #dd524d;
  539. font-weight: bold;
  540. }
  541. }
  542. .uni-forms-item--border {
  543. margin-bottom: 0;
  544. padding: 10px 0;
  545. // padding-bottom: 0;
  546. border-top: 1px #eee solid;
  547. /* #ifndef APP-NVUE */
  548. .uni-forms-item__content {
  549. flex-direction: column;
  550. justify-content: flex-start;
  551. align-items: flex-start;
  552. .uni-forms-item__error {
  553. position: relative;
  554. top: 5px;
  555. left: 0;
  556. padding-top: 0;
  557. }
  558. }
  559. /* #endif */
  560. /* #ifdef APP-NVUE */
  561. display: flex;
  562. flex-direction: column;
  563. .uni-forms-item__error {
  564. position: relative;
  565. top: 0px;
  566. left: 0;
  567. padding-top: 0;
  568. margin-top: 5px;
  569. }
  570. /* #endif */
  571. }
  572. .is-first-border {
  573. /* #ifndef APP-NVUE */
  574. border: none;
  575. /* #endif */
  576. /* #ifdef APP-NVUE */
  577. border-width: 0;
  578. /* #endif */
  579. }
  580. </style>