uni-forms-item.vue 14 KB

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