uni-forms.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <template>
  2. <view class="uni-forms">
  3. <form>
  4. <slot></slot>
  5. </form>
  6. </view>
  7. </template>
  8. <script>
  9. import Validator from './validate.js';
  10. import {
  11. deepCopy,
  12. getValue,
  13. isRequiredField,
  14. setDataValue,
  15. getDataValue,
  16. realName,
  17. isRealName,
  18. rawData,
  19. isEqual
  20. } from './utils.js'
  21. // #ifndef VUE3
  22. // 后续会慢慢废弃这个方法
  23. import Vue from 'vue';
  24. Vue.prototype.binddata = function(name, value, formName) {
  25. if (formName) {
  26. this.$refs[formName].setValue(name, value);
  27. } else {
  28. let formVm;
  29. for (let i in this.$refs) {
  30. const vm = this.$refs[i];
  31. if (vm && vm.$options && vm.$options.name === 'uniForms') {
  32. formVm = vm;
  33. break;
  34. }
  35. }
  36. if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
  37. formVm.setValue(name, value);
  38. }
  39. };
  40. // #endif
  41. /**
  42. * Forms 表单
  43. * @description 由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据
  44. * @tutorial https://ext.dcloud.net.cn/plugin?id=2773
  45. * @property {Object} rules 表单校验规则
  46. * @property {String} validateTrigger = [bind|submit|blur] 校验触发器方式 默认 submit
  47. * @value bind 发生变化时触发
  48. * @value submit 提交时触发
  49. * @value blur 失去焦点时触发
  50. * @property {String} labelPosition = [top|left] label 位置 默认 left
  51. * @value top 顶部显示 label
  52. * @value left 左侧显示 label
  53. * @property {String} labelWidth label 宽度,默认 70px
  54. * @property {String} labelAlign = [left|center|right] label 居中方式 默认 left
  55. * @value left label 左侧显示
  56. * @value center label 居中
  57. * @value right label 右侧对齐
  58. * @property {String} errShowType = [undertext|toast|modal] 校验错误信息提示方式
  59. * @value undertext 错误信息在底部显示
  60. * @value toast 错误信息toast显示
  61. * @value modal 错误信息modal显示
  62. * @event {Function} submit 提交时触发
  63. * @event {Function} validate 校验结果发生变化触发
  64. */
  65. export default {
  66. name: 'uniForms',
  67. emits: ['validate', 'submit'],
  68. options: {
  69. // #ifdef MP-TOUTIAO
  70. virtualHost: false,
  71. // #endif
  72. // #ifndef MP-TOUTIAO
  73. virtualHost: true
  74. // #endif
  75. },
  76. props: {
  77. // 即将弃用
  78. value: {
  79. type: Object,
  80. default () {
  81. return null;
  82. }
  83. },
  84. // vue3 替换 value 属性
  85. modelValue: {
  86. type: Object,
  87. default () {
  88. return null;
  89. }
  90. },
  91. // 1.4.0 开始将不支持 v-model ,且废弃 value 和 modelValue
  92. model: {
  93. type: Object,
  94. default () {
  95. return null;
  96. }
  97. },
  98. // 表单校验规则
  99. rules: {
  100. type: Object,
  101. default () {
  102. return {};
  103. }
  104. },
  105. //校验错误信息提示方式 默认 undertext 取值 [undertext|toast|modal]
  106. errShowType: {
  107. type: String,
  108. default: 'undertext'
  109. },
  110. // 校验触发器方式 默认 bind 取值 [bind|submit]
  111. validateTrigger: {
  112. type: String,
  113. default: 'submit'
  114. },
  115. // label 位置,默认 left 取值 top/left
  116. labelPosition: {
  117. type: String,
  118. default: 'left'
  119. },
  120. // label 宽度
  121. labelWidth: {
  122. type: [String, Number],
  123. default: ''
  124. },
  125. // label 居中方式,默认 left 取值 left/center/right
  126. labelAlign: {
  127. type: String,
  128. default: 'left'
  129. },
  130. border: {
  131. type: Boolean,
  132. default: false
  133. }
  134. },
  135. provide() {
  136. return {
  137. uniForm: this
  138. }
  139. },
  140. data() {
  141. return {
  142. // 表单本地值的记录,不应该与传如的值进行关联
  143. formData: {},
  144. formRules: {}
  145. };
  146. },
  147. computed: {
  148. // 计算数据源变化的
  149. localData() {
  150. const localVal = this.model || this.modelValue || this.value
  151. if (localVal) {
  152. return deepCopy(localVal)
  153. }
  154. return {}
  155. }
  156. },
  157. watch: {
  158. // 监听数据变化 ,暂时不使用,需要单独赋值
  159. // localData: {},
  160. // 监听规则变化
  161. rules: {
  162. handler: function(val, oldVal) {
  163. this.setRules(val)
  164. },
  165. deep: true,
  166. immediate: true
  167. }
  168. },
  169. created() {
  170. // #ifdef VUE3
  171. let getbinddata = getApp().$vm.$.appContext.config.globalProperties.binddata
  172. if (!getbinddata) {
  173. getApp().$vm.$.appContext.config.globalProperties.binddata = function(name, value, formName) {
  174. if (formName) {
  175. this.$refs[formName].setValue(name, value);
  176. } else {
  177. let formVm;
  178. for (let i in this.$refs) {
  179. const vm = this.$refs[i];
  180. if (vm && vm.$options && vm.$options.name === 'uniForms') {
  181. formVm = vm;
  182. break;
  183. }
  184. }
  185. if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
  186. if(formVm.model)formVm.model[name] = value
  187. if(formVm.modelValue)formVm.modelValue[name] = value
  188. if(formVm.value)formVm.value[name] = value
  189. }
  190. }
  191. }
  192. // #endif
  193. // 子组件实例数组
  194. this.childrens = []
  195. // TODO 兼容旧版 uni-data-picker ,新版本中无效,只是避免报错
  196. this.inputChildrens = []
  197. this.setRules(this.rules)
  198. },
  199. methods: {
  200. /**
  201. * 外部调用方法
  202. * 设置规则 ,主要用于小程序自定义检验规则
  203. * @param {Array} rules 规则源数据
  204. */
  205. setRules(rules) {
  206. // TODO 有可能子组件合并规则的时机比这个要早,所以需要合并对象 ,而不是直接赋值,可能会被覆盖
  207. this.formRules = Object.assign({}, this.formRules, rules)
  208. // 初始化校验函数
  209. this.validator = new Validator(rules);
  210. },
  211. /**
  212. * 外部调用方法
  213. * 设置数据,用于设置表单数据,公开给用户使用 , 不支持在动态表单中使用
  214. * @param {Object} key
  215. * @param {Object} value
  216. */
  217. setValue(key, value) {
  218. let example = this.childrens.find(child => child.name === key);
  219. if (!example) return null;
  220. this.formData[key] = getValue(key, value, (this.formRules[key] && this.formRules[key].rules) || [])
  221. return example.onFieldChange(this.formData[key]);
  222. },
  223. /**
  224. * 外部调用方法
  225. * 手动提交校验表单
  226. * 对整个表单进行校验的方法,参数为一个回调函数。
  227. * @param {Array} keepitem 保留不参与校验的字段
  228. * @param {type} callback 方法回调
  229. */
  230. validate(keepitem, callback) {
  231. return this.checkAll(this.formData, keepitem, callback);
  232. },
  233. /**
  234. * 外部调用方法
  235. * 部分表单校验
  236. * @param {Array|String} props 需要校验的字段
  237. * @param {Function} 回调函数
  238. */
  239. validateField(props = [], callback) {
  240. props = [].concat(props);
  241. let invalidFields = {};
  242. this.childrens.forEach(item => {
  243. const name = realName(item.name)
  244. if (props.indexOf(name) !== -1) {
  245. invalidFields = Object.assign({}, invalidFields, {
  246. [name]: this.formData[name]
  247. });
  248. }
  249. });
  250. return this.checkAll(invalidFields, [], callback);
  251. },
  252. /**
  253. * 外部调用方法
  254. * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
  255. * @param {Array|String} props 需要移除校验的字段 ,不填为所有
  256. */
  257. clearValidate(props = []) {
  258. props = [].concat(props);
  259. this.childrens.forEach(item => {
  260. if (props.length === 0) {
  261. item.errMsg = '';
  262. } else {
  263. const name = realName(item.name)
  264. if (props.indexOf(name) !== -1) {
  265. item.errMsg = '';
  266. }
  267. }
  268. });
  269. },
  270. /**
  271. * 外部调用方法 ,即将废弃
  272. * 手动提交校验表单
  273. * 对整个表单进行校验的方法,参数为一个回调函数。
  274. * @param {Array} keepitem 保留不参与校验的字段
  275. * @param {type} callback 方法回调
  276. */
  277. submit(keepitem, callback, type) {
  278. for (let i in this.dataValue) {
  279. const itemData = this.childrens.find(v => v.name === i);
  280. if (itemData) {
  281. if (this.formData[i] === undefined) {
  282. this.formData[i] = this._getValue(i, this.dataValue[i]);
  283. }
  284. }
  285. }
  286. if (!type) {
  287. console.warn('submit 方法即将废弃,请使用validate方法代替!');
  288. }
  289. return this.checkAll(this.formData, keepitem, callback, 'submit');
  290. },
  291. // 校验所有
  292. async checkAll(invalidFields, keepitem, callback, type) {
  293. // 不存在校验规则 ,则停止校验流程
  294. if (!this.validator) return
  295. let childrens = []
  296. // 处理参与校验的item实例
  297. for (let i in invalidFields) {
  298. const item = this.childrens.find(v => realName(v.name) === i)
  299. if (item) {
  300. childrens.push(item)
  301. }
  302. }
  303. // 如果validate第一个参数是funciont ,那就走回调
  304. if (!callback && typeof keepitem === 'function') {
  305. callback = keepitem;
  306. }
  307. let promise;
  308. // 如果不存在回调,那么使用 Promise 方式返回
  309. if (!callback && typeof callback !== 'function' && Promise) {
  310. promise = new Promise((resolve, reject) => {
  311. callback = function(valid, invalidFields) {
  312. !valid ? resolve(invalidFields) : reject(valid);
  313. };
  314. });
  315. }
  316. let results = [];
  317. // 避免引用错乱 ,建议拷贝对象处理
  318. let tempFormData = JSON.parse(JSON.stringify(invalidFields))
  319. // 所有子组件参与校验,使用 for 可以使用 awiat
  320. for (let i in childrens) {
  321. const child = childrens[i]
  322. let name = realName(child.name);
  323. const result = await child.onFieldChange(tempFormData[name]);
  324. if (result) {
  325. results.push(result);
  326. // toast ,modal 只需要执行第一次就可以
  327. if (this.errShowType === 'toast' || this.errShowType === 'modal') break;
  328. }
  329. }
  330. if (Array.isArray(results)) {
  331. if (results.length === 0) results = null;
  332. }
  333. if (Array.isArray(keepitem)) {
  334. keepitem.forEach(v => {
  335. let vName = realName(v);
  336. let value = getDataValue(v, this.localData)
  337. if (value !== undefined) {
  338. tempFormData[vName] = value
  339. }
  340. });
  341. }
  342. // TODO submit 即将废弃
  343. if (type === 'submit') {
  344. this.$emit('submit', {
  345. detail: {
  346. value: tempFormData,
  347. errors: results
  348. }
  349. });
  350. } else {
  351. this.$emit('validate', results);
  352. }
  353. // const resetFormData = rawData(tempFormData, this.localData, this.name)
  354. let resetFormData = {}
  355. resetFormData = rawData(tempFormData, this.name)
  356. callback && typeof callback === 'function' && callback(results, resetFormData);
  357. if (promise && callback) {
  358. return promise;
  359. } else {
  360. return null;
  361. }
  362. },
  363. /**
  364. * 返回validate事件
  365. * @param {Object} result
  366. */
  367. validateCheck(result) {
  368. this.$emit('validate', result);
  369. },
  370. _getValue: getValue,
  371. _isRequiredField: isRequiredField,
  372. _setDataValue: setDataValue,
  373. _getDataValue: getDataValue,
  374. _realName: realName,
  375. _isRealName: isRealName,
  376. _isEqual: isEqual
  377. }
  378. };
  379. </script>
  380. <style lang="scss">
  381. .uni-forms {}
  382. </style>