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.

218 lines
7.4 KiB

2 months ago
  1. <template>
  2. <view class="u-form">
  3. <slot />
  4. </view>
  5. </template>
  6. <script>
  7. import { props } from "./props.js";
  8. import { mpMixin } from '../../libs/mixin/mpMixin';
  9. import { mixin } from '../../libs/mixin/mixin';
  10. import Schema from "../../libs/util/async-validator";
  11. import { toast, getProperty, setProperty, deepClone, error } from '../../libs/function/index';
  12. import test from '../../libs/function/test';
  13. // 去除警告信息
  14. Schema.warning = function() {};
  15. /**
  16. * Form 表单
  17. * @description 此组件一般用于表单场景可以配置Input输入框Select弹出框进行表单验证等
  18. * @tutorial https://ijry.github.io/uview-plus/components/form.html
  19. * @property {Object} model 当前form的需要验证字段的集合
  20. * @property {Object | Function | Array} rules 验证规则
  21. * @property {String} errorType 错误的提示方式见上方说明 ( 默认 message )
  22. * @property {Boolean} borderBottom 是否显示表单域的下划线边框 ( 默认 true
  23. * @property {String} labelPosition 表单域提示文字的位置left-左侧top-上方 ( 默认 'left'
  24. * @property {String | Number} labelWidth 提示文字的宽度单位px ( 默认 45
  25. * @property {String} labelAlign lable字体的对齐方式 ( 默认 left'
  26. * @property {Object} labelStyle lable的样式对象形式
  27. * @example <up-formlabelPosition="left" :model="model1" :rules="rules" ref="form1"></up-form>
  28. */
  29. export default {
  30. name: "u-form",
  31. mixins: [mpMixin, mixin, props],
  32. provide() {
  33. return {
  34. uForm: this,
  35. };
  36. },
  37. data() {
  38. return {
  39. formRules: {},
  40. // 规则校验器
  41. validator: {},
  42. // 原始的model快照,用于resetFields方法重置表单时使用
  43. originalModel: null,
  44. };
  45. },
  46. watch: {
  47. // 监听规则的变化
  48. rules: {
  49. immediate: true,
  50. handler(n) {
  51. this.setRules(n);
  52. },
  53. },
  54. // 监听属性的变化,通知子组件u-form-item重新获取信息
  55. propsChange(n) {
  56. if (this.children?.length) {
  57. this.children.map((child) => {
  58. // 判断子组件(u-form-item)如果有updateParentData方法的话,就就执行(执行的结果是子组件重新从父组件拉取了最新的值)
  59. typeof child.updateParentData == "function" &&
  60. child.updateParentData();
  61. });
  62. }
  63. },
  64. // 监听model的初始值作为重置表单的快照
  65. model: {
  66. immediate: true,
  67. handler(n) {
  68. if (!this.originalModel) {
  69. this.originalModel = deepClone(n);
  70. }
  71. },
  72. },
  73. },
  74. computed: {
  75. propsChange() {
  76. return [
  77. this.errorType,
  78. this.borderBottom,
  79. this.labelPosition,
  80. this.labelWidth,
  81. this.labelAlign,
  82. this.labelStyle,
  83. ];
  84. },
  85. },
  86. created() {
  87. // 存储当前form下的所有u-form-item的实例
  88. // 不能定义在data中,否则微信小程序会造成循环引用而报错
  89. this.children = [];
  90. },
  91. methods: {
  92. // 手动设置校验的规则,如果规则中有函数的话,微信小程序中会过滤掉,所以只能手动调用设置规则
  93. setRules(rules) {
  94. // 判断是否有规则
  95. if (Object.keys(rules).length === 0) return;
  96. if (process.env.NODE_ENV === 'development' && Object.keys(this.model).length === 0) {
  97. error('设置rules,model必须设置!如果已经设置,请刷新页面。');
  98. return;
  99. };
  100. this.formRules = rules;
  101. // 重新将规则赋予Validator
  102. this.validator = new Schema(rules);
  103. },
  104. // 清空所有u-form-item组件的内容,本质上是调用了u-form-item组件中的resetField()方法
  105. resetFields() {
  106. this.resetModel();
  107. },
  108. // 重置model为初始值的快照
  109. resetModel(obj) {
  110. // 历遍所有u-form-item,根据其prop属性,还原model的原始快照
  111. this.children.map((child) => {
  112. const prop = child?.prop;
  113. const value = getProperty(this.originalModel, prop);
  114. setProperty(this.model, prop, value);
  115. });
  116. },
  117. // 清空校验结果
  118. clearValidate(props) {
  119. props = [].concat(props);
  120. this.children.map((child) => {
  121. // 如果u-form-item的prop在props数组中,则清除对应的校验结果信息
  122. if (props[0] === undefined || props.includes(child.prop)) {
  123. child.message = null;
  124. }
  125. });
  126. },
  127. // 对部分表单字段进行校验
  128. async validateField(value, callback, event = null) {
  129. // $nextTick是必须的,否则model的变更,可能会延后于此方法的执行
  130. this.$nextTick(() => {
  131. // 校验错误信息,返回给回调方法,用于存放所有form-item的错误信息
  132. const errorsRes = [];
  133. // 如果为字符串,转为数组
  134. value = [].concat(value);
  135. // 历遍children所有子form-item
  136. this.children.map((child) => {
  137. // 用于存放form-item的错误信息
  138. const childErrors = [];
  139. if (value.includes(child.prop)) {
  140. // 获取对应的属性,通过类似'a.b.c'的形式
  141. const propertyVal = getProperty(
  142. this.model,
  143. child.prop
  144. );
  145. // 属性链数组
  146. const propertyChain = child.prop.split(".");
  147. const propertyName =
  148. propertyChain[propertyChain.length - 1];
  149. const rule = this.formRules[child.rule || child.prop];
  150. // 如果不存在对应的规则,直接返回,否则校验器会报错
  151. if (!rule) return;
  152. // rule规则可为数组形式,也可为对象形式,此处拼接成为数组
  153. const rules = [].concat(rule);
  154. // 对rules数组进行校验
  155. for (let i = 0; i < rules.length; i++) {
  156. const ruleItem = rules[i];
  157. // 将u-form-item的触发器转为数组形式
  158. const trigger = [].concat(ruleItem?.trigger);
  159. // 如果是有传入触发事件,但是此form-item却没有配置此触发器的话,不执行校验操作
  160. if (event && !trigger.includes(event)) continue;
  161. // 实例化校验对象,传入构造规则
  162. const validator = new Schema({
  163. [propertyName]: ruleItem,
  164. });
  165. validator.validate({
  166. [propertyName]: propertyVal,
  167. },
  168. (errors, fields) => {
  169. if (test.array(errors)) {
  170. errorsRes.push(...errors);
  171. childErrors.push(...errors);
  172. }
  173. child.message =
  174. childErrors[0]?.message ? childErrors[0].message : null;
  175. }
  176. );
  177. }
  178. }
  179. });
  180. // 执行回调函数
  181. typeof callback === "function" && callback(errorsRes);
  182. });
  183. },
  184. // 校验全部数据
  185. validate(callback) {
  186. // 开发环境才提示,生产环境不会提示
  187. if (process.env.NODE_ENV === 'development' && Object.keys(this.formRules).length === 0) {
  188. error('未设置rules,请看文档说明!如果已经设置,请刷新页面。');
  189. return;
  190. }
  191. return new Promise((resolve, reject) => {
  192. // $nextTick是必须的,否则model的变更,可能会延后于validate方法
  193. this.$nextTick(() => {
  194. // 获取所有form-item的prop,交给validateField方法进行校验
  195. const formItemProps = this.children.map(
  196. (item) => item.prop
  197. );
  198. this.validateField(formItemProps, (errors) => {
  199. if(errors.length) {
  200. // 如果错误提示方式为toast,则进行提示
  201. this.errorType === 'toast' && toast(errors[0].message)
  202. reject(errors)
  203. } else {
  204. resolve(true)
  205. }
  206. });
  207. });
  208. });
  209. },
  210. },
  211. };
  212. </script>
  213. <style lang="scss" scoped>
  214. </style>