u-form.vue 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <template>
  2. <view class="u-form">
  3. <slot />
  4. </view>
  5. </template>
  6. <script>
  7. import props from "./props.js"
  8. import mixin from '../../libs/mixin/mixin'
  9. import mpMixin from '../../libs/mixin/mpMixin'
  10. import Schema from "../../libs/util/async-validator"
  11. // 去除警告信息
  12. Schema.warning = function() {};
  13. /**
  14. * Form 表单
  15. * @description 此组件一般用于表单场景,可以配置Input输入框,Select弹出框,进行表单验证等。
  16. * @tutorial https://uview.d3u.cn/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} borderBottomColor 下划线边框的颜色
  22. * @property {String} errorType 错误的提示方式,见上方说明 ( 默认 message )
  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 <u--form labelPosition="left" :model="model1" :rules="rules" ref="form1"></u--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. this.$u.test.func(child.updateParentData) && 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.borderBottomColor,
  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. // 手动设置校验的规则,vue2中如果规则中有函数的话,微信小程序中会过滤掉,所以只能手动调用设置规则
  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() {
  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. this.$emit('update:model', this.model)
  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 asyncSchema(propertyName, propertyVal, ruleItem){
  129. return new Promise(async (resolve, reject) => {
  130. const validator = new Schema({
  131. [propertyName]: ruleItem
  132. });
  133. validator.validate({ [propertyName]: propertyVal }, (errors, fields) => {
  134. resolve({errors, fields})
  135. });
  136. });
  137. },
  138. // 对部分表单字段进行校验
  139. async validateField(value, callback, event = null) {
  140. // $nextTick是必须的,否则model的变更,可能会延后于此方法的执行
  141. await this.$nextTick();
  142. // 如果为字符串,转为数组
  143. value = [].concat(value);
  144. // 历遍children所有子form-item
  145. let promises = this.children.map((child) => {
  146. return new Promise(async (resolve, reject) => {
  147. // 用于存放form-item的错误信息
  148. const childErrors = [];
  149. if (value.includes(child.prop) === false) {
  150. return resolve()
  151. }
  152. // 获取对应的属性,通过类似'a.b.c'的形式
  153. const propertyVal = uni.$u.getProperty(
  154. this.model,
  155. child.prop
  156. );
  157. // 属性链数组
  158. const propertyChain = child.prop.split(".");
  159. const propertyName = propertyChain[propertyChain.length - 1];
  160. let rule = this.formRules[child.prop];
  161. if(child.itemRules && Object.keys(child.itemRules).length > 0){
  162. rule = child.itemRules;
  163. }
  164. // 如果不存在对应的规则,直接返回,否则校验器会报错
  165. if (!rule){
  166. return resolve()
  167. }
  168. // rule规则可为数组形式,也可为对象形式,此处拼接成为数组
  169. const rules = [].concat(rule);
  170. if(!rules.length){
  171. return resolve()
  172. }
  173. // 对rules数组进行校验
  174. for (let i = 0; i < rules.length; i++) {
  175. const ruleItem = rules[i];
  176. // 将u-form-item的触发器转为数组形式
  177. if(ruleItem.hasOwnProperty('trigger')){
  178. const trigger = [].concat(ruleItem.trigger);
  179. // 如果是有传入触发事件,但是此form-item却没有配置此触发器的话,不执行校验操作
  180. if (event && !trigger.includes(event)) continue;
  181. }
  182. const { errors } = await this.asyncSchema(propertyName, propertyVal, ruleItem);
  183. if (uni.$u.test.array(errors)) {
  184. errors.forEach(item => {
  185. item.prop = child.prop;
  186. childErrors.push(item);
  187. })
  188. child.message = childErrors[0].hasOwnProperty('message') ? childErrors[0].message : null;
  189. }else{
  190. child.message = null;
  191. }
  192. }
  193. resolve(childErrors)
  194. });
  195. });
  196. Promise.all(promises).then(results => {
  197. const flatResults = [].concat.apply([], results);
  198. const filteredResults = flatResults.filter(item => !!item);
  199. uni.$u.test.func(callback) && callback(filteredResults);
  200. })
  201. },
  202. // 校验全部数据
  203. validate(callback) {
  204. // 开发环境才提示,生产环境不会提示
  205. if (process.env.NODE_ENV === 'development' && Object.keys(this.formRules).length === 0) {
  206. uni.$u.error('未设置rules,请看文档说明!如果已经设置,请刷新页面。');
  207. return;
  208. }
  209. return new Promise((resolve, reject) => {
  210. // $nextTick是必须的,否则model的变更,可能会延后于validate方法
  211. this.$nextTick(() => {
  212. // 获取所有form-item的prop,交给validateField方法进行校验
  213. const formItemProps = this.children.map(
  214. (item) => item.prop
  215. );
  216. this.validateField(formItemProps, (errors) => {
  217. if(errors && errors.length > 0) {
  218. // 如果错误提示方式为toast,则进行提示
  219. this.errorType === 'toast' && uni.$u.toast(errors[0].message)
  220. reject(errors)
  221. } else {
  222. resolve(true)
  223. }
  224. });
  225. });
  226. });
  227. },
  228. },
  229. };
  230. </script>
  231. <style lang="scss" scoped>
  232. </style>