u-form.vue 7.5 KB

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