u-form-item.vue 13 KB

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