AI销管
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

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