u-form.vue 7.5 KB

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