Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

397 rindas
12 KiB

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