u-form-item.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <template>
  2. <view class="u-form-item"
  3. :class="{'u-border-bottom': elBorderBottom, 'u-form-item__border-bottom--error': validateState === 'error' && showError('border-bottom')}">
  4. <view class="u-form-item__body" :style="{
  5. flexDirection: elLabelPosition == 'left' ? 'row' : 'column'
  6. }">
  7. <!-- 微信小程序中,将一个参数设置空字符串,结果会变成字符串"true" -->
  8. <view class="u-form-item--left" :style="{
  9. width: uLabelWidth,
  10. flex: `0 0 ${uLabelWidth}`,
  11. marginBottom: elLabelPosition == 'left' ? 0 : '10rpx',
  12. }">
  13. <!-- 为了块对齐 -->
  14. <view class="u-form-item--left__content" v-if="required || leftIcon || label">
  15. <!-- nvue不支持伪元素before -->
  16. <!-- <text v-if="required" class="u-form-item--left__content--required">*</text> -->
  17. <view class="u-form-item--left__content__label" :style="[elLabelStyle, {
  18. 'justify-content': elLabelAlign == 'left' ? 'flex-start' : elLabelAlign == 'center' ? 'center' : 'flex-end'
  19. }]" @click="clickIcon">
  20. <text v-if="required" style="color: red;">*</text>
  21. <view>
  22. <span>{{label}}</span>
  23. <view class="u-form-item--left__content__icon" v-if="leftIcon">
  24. <u-icon :name="leftIcon" :custom-style="leftIconStyle"></u-icon>
  25. </view>
  26. </view>
  27. </view>
  28. </view>
  29. </view>
  30. <view class="u-form-item--right u-flex">
  31. <view class="u-form-item--right__content">
  32. <view class="u-form-item--right__content__slot"
  33. :style="elLabelPosition == 'left' && elInputAlign == 'right' ? 'text-align:right;display: inline-block;line-height:initial;' : ''">
  34. <slot />
  35. </view>
  36. <view class="u-form-item--right__content__icon u-flex" v-if="$slots.right || rightIcon">
  37. <u-icon :custom-style="rightIconStyle" v-if="rightIcon" :name="rightIcon"></u-icon>
  38. <slot name="right" />
  39. </view>
  40. </view>
  41. </view>
  42. </view>
  43. <view class="u-form-item__message" v-if="validateState === 'error' && showError('message')" :style="{
  44. paddingLeft: elLabelPosition == 'left' ? $u.addUnit(elLabelWidth) : '0',
  45. textAlign: elInputAlign == 'right' ? 'right' : 'left'
  46. }">{{validateMessage}}</view>
  47. </view>
  48. </template>
  49. <script>
  50. import Emitter from '../../libs/util/emitter.js';
  51. import schema from '../../libs/util/async-validator';
  52. // 去除警告信息
  53. schema.warning = function() {};
  54. /**
  55. * form-item 表单item
  56. * @description 此组件一般用于表单场景,可以配置Input输入框,Select弹出框,进行表单验证等。
  57. * @tutorial https://vkuviewdoc.fsq.pub/components/form.html
  58. * @property {String} label 左侧提示文字
  59. * @property {Object} prop 表单域model对象的属性名,在使用 validate、resetFields 方法的情况下,该属性是必填的
  60. * @property {Boolean} border-bottom 是否显示表单域的下划线边框
  61. * @property {String} label-position 表单域提示文字的位置,left-左侧,top-上方
  62. * @property {String Number} label-width 提示文字的宽度,单位rpx(默认90)
  63. * @property {Object} label-style lable的样式,对象形式
  64. * @property {String} label-align lable的对齐方式
  65. * @property {String} right-icon 右侧自定义字体图标(限uView内置图标)或图片地址
  66. * @property {String} left-icon 左侧自定义字体图标(限uView内置图标)或图片地址
  67. * @property {Object} left-icon-style 左侧图标的样式,对象形式
  68. * @property {Object} right-icon-style 右侧图标的样式,对象形式
  69. * @property {Boolean} required 是否显示左边的"*"号,这里仅起展示作用,如需校验必填,请通过rules配置必填规则(默认false)
  70. * @example <u-form-item label="姓名"><u-input v-model="form.name" /></u-form-item>
  71. */
  72. export default {
  73. name: 'u-form-item',
  74. mixins: [Emitter],
  75. inject: {
  76. uForm: {
  77. default () {
  78. return null
  79. }
  80. }
  81. },
  82. props: {
  83. // input的label提示语
  84. label: {
  85. type: String,
  86. default: ''
  87. },
  88. // 绑定的值
  89. prop: {
  90. type: String,
  91. default: ''
  92. },
  93. // 是否显示表单域的下划线边框
  94. borderBottom: {
  95. type: [String, Boolean],
  96. default: ''
  97. },
  98. // label的位置,left-左边,top-上边
  99. labelPosition: {
  100. type: String,
  101. default: ''
  102. },
  103. // label的宽度,单位rpx
  104. labelWidth: {
  105. type: [String, Number],
  106. default: ''
  107. },
  108. // lable的样式,对象形式
  109. labelStyle: {
  110. type: Object,
  111. default () {
  112. return {}
  113. }
  114. },
  115. // lable字体的对齐方式
  116. labelAlign: {
  117. type: String,
  118. default: ''
  119. },
  120. // 右侧图标
  121. rightIcon: {
  122. type: String,
  123. default: ''
  124. },
  125. // 左侧图标
  126. leftIcon: {
  127. type: String,
  128. default: ''
  129. },
  130. // 左侧图标的样式
  131. leftIconStyle: {
  132. type: Object,
  133. default () {
  134. return {}
  135. }
  136. },
  137. // 左侧图标的样式
  138. rightIconStyle: {
  139. type: Object,
  140. default () {
  141. return {}
  142. }
  143. },
  144. // 是否显示左边的必填星号,只作显示用,具体校验必填的逻辑,请在rules中配置
  145. required: {
  146. type: Boolean,
  147. default: false
  148. },
  149. inputAlign: {
  150. type: String,
  151. default: ''
  152. },
  153. },
  154. data() {
  155. return {
  156. initialValue: '', // 存储的默认值
  157. // isRequired: false, // 是否必填,由于人性化考虑,必填"*"号通过props的required配置,不再通过rules的规则自动生成
  158. validateState: '', // 是否校验成功
  159. validateMessage: '', // 校验失败的提示语
  160. // 有错误时的提示方式,message-提示信息,border-如果input设置了边框,变成呈红色,
  161. errorType: ['message'],
  162. fieldValue: '', // 获取当前子组件input的输入的值
  163. // 父组件的参数,在computed计算中,无法得知this.parent发生变化,故将父组件的参数值,放到data中
  164. parentData: {
  165. borderBottom: true,
  166. labelWidth: 90,
  167. labelPosition: 'left',
  168. labelStyle: {},
  169. labelAlign: 'left',
  170. inputAlign: 'left',
  171. }
  172. };
  173. },
  174. watch: {
  175. validateState(val) {
  176. this.broadcastInputError();
  177. },
  178. // 监听u-form组件的errorType的变化
  179. "uForm.errorType"(val) {
  180. this.errorType = val;
  181. this.broadcastInputError();
  182. },
  183. },
  184. computed: {
  185. // 计算后的label宽度,由于需要多个判断,故放到computed中
  186. uLabelWidth() {
  187. // 如果用户设置label为空字符串(微信小程序空字符串最终会变成字符串的'true'),意味着要将label的位置宽度设置为auto
  188. return this.elLabelPosition == 'left' ? (this.label === 'true' || this.label === '' ? 'auto' : this.$u
  189. .addUnit(this
  190. .elLabelWidth)) : '100%';
  191. },
  192. showError() {
  193. return type => {
  194. // 如果errorType数组中含有none,或者toast提示类型
  195. if (this.errorType.indexOf('none') >= 0) return false;
  196. else if (this.errorType.indexOf(type) >= 0) return true;
  197. else return false;
  198. }
  199. },
  200. // label的宽度
  201. elLabelWidth() {
  202. // label默认宽度为90,优先使用本组件的值,如果没有(如果设置为0,也算是配置了值,依然起效),则用u-form的值
  203. return (this.labelWidth != 0 || this.labelWidth != '') ? this.labelWidth : (this.parentData.labelWidth ?
  204. this.parentData
  205. .labelWidth :
  206. 90);
  207. },
  208. // label的样式
  209. elLabelStyle() {
  210. return Object.keys(this.labelStyle).length ? this.labelStyle : (this.parentData.labelStyle ? this
  211. .parentData.labelStyle : {});
  212. },
  213. // label的位置,左侧或者上方
  214. elLabelPosition() {
  215. return this.labelPosition ? this.labelPosition : (this.parentData.labelPosition ? this.parentData
  216. .labelPosition :
  217. 'left');
  218. },
  219. // label的对齐方式
  220. elLabelAlign() {
  221. return this.labelAlign ? this.labelAlign : (this.parentData.labelAlign ? this.parentData.labelAlign :
  222. 'left');
  223. },
  224. // label的下划线
  225. elBorderBottom() {
  226. // 子组件的borderBottom默认为空字符串,如果不等于空字符串,意味着子组件设置了值,优先使用子组件的值
  227. return this.borderBottom !== '' ? this.borderBottom : this.parentData.borderBottom ? this.parentData
  228. .borderBottom :
  229. true;
  230. },
  231. elInputAlign() {
  232. return this.inputAlign ? this.inputAlign : (this.parentData.inputAlign ? this.parentData.inputAlign :
  233. 'left');
  234. },
  235. },
  236. methods: {
  237. clickIcon() {
  238. this.$emit('clickIcon')
  239. },
  240. broadcastInputError() {
  241. // 子组件发出事件,第三个参数为true或者false,true代表有错误
  242. this.broadcast('u-input', 'onFormItemError', this.validateState === 'error' && this.showError('border'));
  243. },
  244. // 判断是否需要required校验
  245. setRules() {
  246. let that = this;
  247. // 由于人性化考虑,必填"*"号通过props的required配置,不再通过rules的规则自动生成
  248. // 从父组件u-form拿到当前u-form-item需要验证 的规则
  249. // let rules = this.getRules();
  250. // if (rules.length) {
  251. // this.isRequired = rules.some(rule => {
  252. // // 如果有必填项,就返回,没有的话,就是undefined
  253. // return rule.required;
  254. // });
  255. // }
  256. // #ifndef VUE3
  257. // blur事件
  258. this.$on('onFieldBlur', that.onFieldBlur);
  259. // change事件
  260. this.$on('onFieldChange', that.onFieldChange);
  261. // #endif
  262. // #ifdef VUE3
  263. // #endif
  264. },
  265. // 从u-form的rules属性中,取出当前u-form-item的校验规则
  266. getRules() {
  267. // 父组件的所有规则
  268. let rules = this.parent.rules;
  269. rules = rules ? rules[this.prop] : [];
  270. // 保证返回的是一个数组形式
  271. return [].concat(rules || []);
  272. },
  273. // blur事件时进行表单校验
  274. onFieldBlur() {
  275. this.validation('blur');
  276. },
  277. // change事件进行表单校验
  278. onFieldChange() {
  279. this.validation('change');
  280. },
  281. // 过滤出符合要求的rule规则
  282. getFilteredRule(triggerType = '') {
  283. let rules = this.getRules();
  284. // 整体验证表单时,triggerType为空字符串,此时返回所有规则进行验证
  285. if (!triggerType) return rules;
  286. // 历遍判断规则是否有对应的事件,比如blur,change触发等的事件
  287. // 使用indexOf判断,是因为某些时候设置的验证规则的trigger属性可能为多个,比如['blur','change']
  288. // 某些场景可能的判断规则,可能不存在trigger属性,故先判断是否存在此属性
  289. return rules.filter(res => res.trigger && res.trigger.indexOf(triggerType) !== -1);
  290. },
  291. getData(dataObj, name, defaultValue) {
  292. let newDataObj;
  293. if (dataObj) {
  294. newDataObj = JSON.parse(JSON.stringify(dataObj));
  295. let k = "",
  296. d = ".",
  297. l = "[",
  298. r = "]";
  299. name = name.replace(/\s+/g, k) + d;
  300. let tstr = k;
  301. for (let i = 0; i < name.length; i++) {
  302. let theChar = name.charAt(i);
  303. if (theChar != d && theChar != l && theChar != r) {
  304. tstr += theChar;
  305. } else if (newDataObj) {
  306. if (tstr != k) newDataObj = newDataObj[tstr];
  307. tstr = k;
  308. }
  309. }
  310. }
  311. if (typeof newDataObj === "undefined" && typeof defaultValue !== "undefined") newDataObj = defaultValue;
  312. return newDataObj;
  313. },
  314. setData(dataObj, name, value) {
  315. // 通过正则表达式 查找路径数据
  316. let dataValue;
  317. if (typeof value === "object") {
  318. dataValue = JSON.parse(JSON.stringify(value));
  319. } else {
  320. dataValue = value;
  321. }
  322. let regExp = new RegExp("([\\w$]+)|\\[(:\\d)\\]", "g");
  323. const patten = name.match(regExp);
  324. // 遍历路径 逐级查找 最后一级用于直接赋值
  325. for (let i = 0; i < patten.length - 1; i++) {
  326. let keyName = patten[i];
  327. if (typeof dataObj[keyName] !== "object") dataObj[keyName] = {};
  328. dataObj = dataObj[keyName];
  329. }
  330. // 最后一级
  331. dataObj[patten[patten.length - 1]] = dataValue;
  332. },
  333. // 校验数据
  334. validation(trigger, callback = () => {}) {
  335. // 检验之间,先获取需要校验的值
  336. //this.fieldValue = this.parent.model[this.prop];
  337. // 修改支持a.b
  338. this.fieldValue = this.getData(this.parent.model, this.prop);
  339. // blur和change是否有当前方式的校验规则
  340. let rules = this.getFilteredRule(trigger);
  341. // 判断是否有验证规则,如果没有规则,也调用回调方法,否则父组件u-form会因为
  342. // 对count变量的统计错误而无法进入上一层的回调
  343. if (!rules || rules.length === 0) {
  344. return callback('');
  345. }
  346. // 设置当前的装填,标识为校验中
  347. this.validateState = 'validating';
  348. // 调用async-validator的方法
  349. let validator = new schema({
  350. [this.prop]: rules
  351. });
  352. validator.validate({
  353. [this.prop]: this.fieldValue
  354. }, {
  355. firstFields: true
  356. }, (errors, fields) => {
  357. // 记录状态和报错信息
  358. this.validateState = !errors ? 'success' : 'error';
  359. this.validateMessage = errors ? errors[0].message : '';
  360. let field = errors ? errors[0].field : '';
  361. // 调用回调方法
  362. callback(this.validateMessage, {
  363. state: this.validateState,
  364. key: field,
  365. msg: this.validateMessage
  366. });
  367. });
  368. },
  369. // 清空当前的u-form-item
  370. resetField() {
  371. //this.parent.model[this.prop] = this.initialValue;
  372. this.setData(this.parent.model, this.prop, this.initialValue);
  373. // 设置为`success`状态,只是为了清空错误标记
  374. this.validateState = 'success';
  375. }
  376. },
  377. // 组件创建完成时,将当前实例保存到u-form中
  378. mounted() {
  379. // 支付宝、头条小程序不支持provide/inject,所以使用这个方法获取整个父组件,在created定义,避免循环应用
  380. this.parent = this.$u.$parent.call(this, 'u-form');
  381. if (this.parent) {
  382. // 历遍parentData中的属性,将parent中的同名属性赋值给parentData
  383. Object.keys(this.parentData).map(key => {
  384. this.parentData[key] = this.parent[key];
  385. });
  386. // 如果没有传入prop,或者uForm为空(如果u-form-input单独使用,就不会有uForm注入),就不进行校验
  387. if (this.prop) {
  388. // 将本实例添加到父组件中
  389. this.parent.fields.push(this);
  390. this.errorType = this.parent.errorType;
  391. this.fieldValue = this.parent.model[this.prop];
  392. // 设置初始值
  393. this.initialValue = this.fieldValue;
  394. // 添加表单校验,这里必须要写在$nextTick中,因为u-form的rules是通过ref手动传入的
  395. // 不在$nextTick中的话,可能会造成执行此处代码时,父组件还没通过ref把规则给u-form,导致规则为空
  396. this.$nextTick(() => {
  397. this.setRules();
  398. })
  399. }
  400. }
  401. },
  402. // #ifndef VUE3
  403. // 组件销毁前,将实例从u-form的缓存中移除
  404. beforeDestroy() {
  405. // 如果当前没有prop的话表示当前不要进行删除(因为没有注入)
  406. if (this.parent && this.prop) {
  407. this.parent.fields.map((item, index) => {
  408. if (item === this) this.parent.fields.splice(index, 1);
  409. })
  410. }
  411. },
  412. // #endif
  413. // #ifdef VUE3
  414. beforeUnmount() {
  415. // 如果当前没有prop的话表示当前不要进行删除(因为没有注入)
  416. if (this.parent && this.prop) {
  417. this.parent.fields.map((item, index) => {
  418. if (item === this) this.parent.fields.splice(index, 1);
  419. })
  420. }
  421. },
  422. // #endif
  423. };
  424. </script>
  425. <style lang="scss" scoped>
  426. @import "../../libs/css/style.components.scss";
  427. .u-form-item {
  428. @include vue-flex;
  429. // align-items: flex-start;
  430. padding: 20rpx 0;
  431. font-size: 28rpx;
  432. color: $u-main-color;
  433. box-sizing: border-box;
  434. line-height: $u-form-item-height;
  435. flex-direction: column;
  436. &__border-bottom--error:after {
  437. border-color: $u-type-error;
  438. }
  439. &__body {
  440. @include vue-flex;
  441. }
  442. &--left {
  443. @include vue-flex;
  444. align-items: center;
  445. &__content {
  446. position: relative;
  447. @include vue-flex;
  448. align-items: center;
  449. padding-right: 10rpx;
  450. flex: 1;
  451. &__icon {
  452. margin-right: 0;
  453. display: inline-block;
  454. }
  455. &--required {
  456. position: absolute;
  457. left: -16rpx;
  458. vertical-align: middle;
  459. color: $u-type-error;
  460. padding-top: 6rpx;
  461. }
  462. &__label {
  463. @include vue-flex;
  464. align-items: center;
  465. flex: 1;
  466. }
  467. }
  468. }
  469. &--right {
  470. flex: 1;
  471. &__content {
  472. @include vue-flex;
  473. align-items: center;
  474. flex: 1;
  475. &__slot {
  476. flex: 1;
  477. /* #ifndef MP */
  478. @include vue-flex;
  479. align-items: center;
  480. /* #endif */
  481. }
  482. &__icon {
  483. margin-left: 10rpx;
  484. color: $u-light-color;
  485. font-size: 30rpx;
  486. }
  487. }
  488. }
  489. &__message {
  490. font-size: 24rpx;
  491. line-height: 24rpx;
  492. color: $u-type-error;
  493. margin-top: 12rpx;
  494. }
  495. }
  496. </style>