u-form.vue 7.2 KB

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