u-form-item.vue 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <template>
  2. <view class="u-form-item" :class="{'u-border-bottom': borderBottom, 'u-form-item__border-bottom--error': validateState === 'error' && showError('border-bottom')}">
  3. <view class="u-form-item__body" :style="{
  4. flexDirection: labelPosition == 'left' ? 'row' : 'column'
  5. }">
  6. <view class="u-form-item--left" :style="{
  7. width: labelPosition == 'left' ? getLabelWidth : '100%',
  8. flex: `0 0 ${labelPosition == 'left' ? getLabelWidth : '100%'}`,
  9. marginBottom: labelPosition == 'left' ? 0 : '10rpx',
  10. }">
  11. <!-- 为了块对齐 -->
  12. <view class="u-form-item--left__content">
  13. <!-- nvue不支持伪元素before -->
  14. <text v-if="isRequired" class="u-form-item--left__content--required">*</text>
  15. <view class="u-form-item--left__content__icon" v-if="leftIcon">
  16. <u-icon :name="leftIcon" :custom-style="leftIconStyle"></u-icon>
  17. </view>
  18. <view class="u-form-item--left__content__label" :style="[labelStyle, {
  19. 'justify-content': labelAlign == 'left' ? 'flex-star' : labelAlign == 'center' ? 'center' : 'flex-end'
  20. }]">
  21. {{label}}
  22. </view>
  23. </view>
  24. </view>
  25. <view class="u-form-item--right u-flex">
  26. <view class="u-form-item--right__content">
  27. <view class="u-form-item--right__content__slot ">
  28. <slot />
  29. </view>
  30. <view class="u-form-item--right__content__icon u-flex" v-if="$slots.right || rightIcon">
  31. <u-icon :custom-style="rightIconStyle" v-if="rightIcon" :name="rightIcon"></u-icon>
  32. <slot name="right" />
  33. </view>
  34. </view>
  35. </view>
  36. </view>
  37. <view class="u-form-item__message" v-if="validateState === 'error' && showError('message')" :style="{
  38. paddingLeft: labelPosition == 'left' ? getLabelWidth : '0',
  39. }">{{validateMessage}}</view>
  40. </view>
  41. </template>
  42. <script>
  43. import Emitter from '../../libs/util/emitter.js';
  44. import schema from '../../libs/util/async-validator';
  45. // 去除警告信息
  46. schema.warning = function(){};
  47. export default {
  48. name: 'u-form-item',
  49. mixins: [Emitter],
  50. inject: {
  51. uForm: {
  52. default() {
  53. return null
  54. }
  55. }
  56. },
  57. props: {
  58. // input的label提示语
  59. label: {
  60. type: String,
  61. default: ''
  62. },
  63. // 绑定的值
  64. prop: {
  65. type: String,
  66. default: ''
  67. },
  68. // 是否显示表单域的下划线边框
  69. borderBottom: {
  70. type: Boolean,
  71. default: true
  72. },
  73. // label的位置,left-左边,top-上边
  74. labelPosition: {
  75. type: String,
  76. default: 'left'
  77. },
  78. // label的宽度,单位rpx
  79. labelWidth: {
  80. type: [String, Number],
  81. default: 90
  82. },
  83. // lable的样式,对象形式
  84. labelStyle: {
  85. type: Object,
  86. default() {
  87. return {}
  88. }
  89. },
  90. // lable字体的对齐方式
  91. labelAlign: {
  92. type: String,
  93. default: 'left'
  94. },
  95. // 右侧图标
  96. rightIcon: {
  97. type: String,
  98. default: ''
  99. },
  100. // 左侧图标
  101. leftIcon: {
  102. type: String,
  103. default: ''
  104. },
  105. // 左侧图标的样式
  106. leftIconStyle: {
  107. type: Object,
  108. default() {
  109. return {}
  110. }
  111. },
  112. // 左侧图标的样式
  113. rightIconStyle: {
  114. type: Object,
  115. default() {
  116. return {}
  117. }
  118. }
  119. },
  120. data() {
  121. return {
  122. initialValue: '', // 存储的默认值
  123. isRequired: false, // 是否必填
  124. validateState: '', // 是否校验成功
  125. validateMessage: '' ,// 校验失败的提示语
  126. // 有错误时的提示方式,message-提示信息,border-如果input设置了边框,变成呈红色,
  127. // border-bottom-下边框呈现红色,none-无提示
  128. errorType: ['message']
  129. };
  130. },
  131. watch: {
  132. validateState(val) {
  133. this.broadcastInputError();
  134. },
  135. // 监听u-form组件的errorType的变化
  136. "uForm.errorType"(val) {
  137. this.errorType = val;
  138. this.broadcastInputError();
  139. }
  140. },
  141. computed: {
  142. fieldValue() {
  143. return this.uForm.model[this.prop];
  144. },
  145. showError() {
  146. return type => {
  147. // 如果errorType数组中含有none,就不提示错误信息
  148. if(this.errorType.indexOf('none') >= 0) return false;
  149. else if(this.errorType.indexOf(type) >= 0) return true;
  150. else return false;
  151. }
  152. },
  153. // 获取labelWidth的值
  154. getLabelWidth() {
  155. return this.labelWidth == 'auto' ? 'auto' : this.labelWidth + 'rpx';
  156. }
  157. },
  158. methods: {
  159. broadcastInputError() {
  160. // 子组件发出事件,第三个参数为true或者false,true代表有错误
  161. this.broadcast('u-input', 'on-form-item-error', this.validateState === 'error' && this.showError('border'));
  162. },
  163. // 判断是否需要required校验
  164. setRules() {
  165. let that = this;
  166. // 从父组件u-form拿到当前u-form-item需要验证 的规则
  167. let rules = this.getRules();
  168. if (rules.length) {
  169. this.isRequired = rules.some(rule => {
  170. // 如果有必填项,就返回,没有的话,就是undefined
  171. return rule.required;
  172. });
  173. }
  174. // blur事件
  175. this.$on('on-form-blur', that.onFieldBlur);
  176. // change事件
  177. this.$on('on-form-change', that.onFieldChange);
  178. },
  179. // 从u-form的rules属性中,取出当前u-form-item的校验规则
  180. getRules() {
  181. // 父组件的所有规则
  182. let rules = this.uForm.rules;
  183. rules = rules ? rules[this.prop] : [];
  184. // 保证返回的是一个数组形式
  185. return [].concat(rules || []);
  186. },
  187. // blur事件时进行表单校验
  188. onFieldBlur() {
  189. this.validation('blur');
  190. },
  191. // change事件进行表单校验
  192. onFieldChange() {
  193. this.validation('change');
  194. },
  195. // 过滤出符合要求的rule规则
  196. getFilteredRule(triggerType = '') {
  197. let rules = this.getRules();
  198. // 整体验证表单时,triggerType为空字符串,此时返回所有规则进行验证
  199. if(!triggerType) return rules;
  200. // 历遍判断规则是否有对应的事件,比如blur,change触发等的事件
  201. // 使用indexOf判断,是因为某些时候设置的验证规则的trigger属性可能为多个,比如['blur','change']
  202. return rules.filter(res => res.trigger == triggerType || res.trigger.indexOf(triggerType) !== -1);
  203. },
  204. // 校验数据
  205. validation(trigger, callback = () => {}) {
  206. // blur和change是否有当前方式的校验规则
  207. let rules = this.getFilteredRule(trigger);
  208. // 判断是否有验证规则,如果没有规则,也调用回调方法,否则父组件u-form会因为
  209. // 对count变量的统计错误而无法进入上一层的回调
  210. if (!rules || rules.length === 0) {
  211. return callback('');
  212. }
  213. // 设置当前的装填,标识为校验中
  214. this.validateState = 'validating';
  215. // 调用async-validator的方法
  216. let validator = new schema({ [this.prop]: rules });
  217. validator.validate({ [this.prop]: this.fieldValue }, { firstFields: true }, (errors, fields) => {
  218. // 记录状态和报错信息
  219. this.validateState = !errors ? 'success' : 'error';
  220. this.validateMessage = errors ? errors[0].message : '';
  221. // 调用回调方法
  222. callback(this.validateMessage);
  223. });
  224. },
  225. // 清空当前的u-form-item
  226. resetField() {
  227. this.uForm.model[this.prop] = this.initialValue;
  228. // 设置为`success`状态,只是为了清空错误标记
  229. this.validateState = 'success';
  230. }
  231. },
  232. // 组件创建完成时,将当前实例保存到u-form中
  233. mounted() {
  234. // 如果没有传入prop,或者uForm为空(如果u-form-input单独使用,就不会有uForm注入),就不进行校验
  235. if (!this.prop || this.uForm === null) return;
  236. // 发出事件,让父组件将本实例加入到管理数组中
  237. this.dispatch('u-form', 'on-form-item-add', this);
  238. this.errorType = this.uForm.errorType;
  239. // 设置初始值
  240. this.initialValue = this.fieldValue;
  241. // 添加表单校验,这里必须要写在$nextTick中,因为u-form的rules是通过ref手动传入的
  242. // 不在$nextTick中的话,可能会造成执行此处代码时,父组件还没通过ref把规则给u-form,导致规则为空
  243. this.$nextTick(() =>{
  244. this.setRules();
  245. })
  246. },
  247. // 组件销毁前,将实例从 Form 的缓存中移除
  248. beforeDestroy() {
  249. this.dispatch('u-form', 'on-form-item-remove', this);
  250. },
  251. };
  252. </script>
  253. <style lang="scss" scoped>
  254. .u-form-item {
  255. display: flex;
  256. // align-items: flex-start;
  257. padding: 20rpx 0;
  258. font-size: 28rpx;
  259. color: $u-main-color;
  260. box-sizing: border-box;
  261. line-height: $u-form-item-height;
  262. flex-direction: column;
  263. &__border-bottom--error:after {
  264. border-color: $u-type-error;
  265. }
  266. &__body {
  267. display: flex;
  268. }
  269. &--left {
  270. display: flex;
  271. align-items: center;
  272. &__content {
  273. position: relative;
  274. display: flex;
  275. align-items: center;
  276. padding-right: 10rpx;
  277. flex: 1;
  278. &__icon {
  279. margin-right: 8rpx;
  280. }
  281. &--required {
  282. position: absolute;
  283. left: -16rpx;
  284. vertical-align: middle;
  285. color: $u-type-error;
  286. padding-top: 6rpx;
  287. }
  288. &__label {
  289. display: flex;
  290. align-items: center;
  291. flex: 1;
  292. }
  293. }
  294. }
  295. &--right {
  296. flex: 1;
  297. &__content {
  298. display: flex;
  299. align-items: center;
  300. flex: 1;
  301. &__slot {
  302. flex: 1;
  303. /* #ifndef MP */
  304. display: flex;
  305. align-items: center;
  306. /* #endif */
  307. }
  308. &__icon {
  309. margin-left: 10rpx;
  310. }
  311. }
  312. }
  313. &__message {
  314. font-size: 24rpx;
  315. line-height: 24rpx;
  316. color: $u-type-error;
  317. margin-top: 12rpx;
  318. }
  319. }
  320. </style>