u-form-item.vue 14 KB

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