u-form-item.vue 14 KB

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