uni-forms.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <template>
  2. <!-- -->
  3. <view class="uni-forms" :class="{'uni-forms--top':!border}">
  4. <form @submit.stop="submitForm" @reset="resetForm">
  5. <slot></slot>
  6. </form>
  7. </view>
  8. </template>
  9. <script>
  10. /**
  11. * Forms 表单
  12. * @description 由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据
  13. * @tutorial https://ext.dcloud.net.cn/plugin?id=2773
  14. * @property {Object} rules 表单校验规则
  15. * @property {String} validateTrigger = [bind|submit] 校验触发器方式 默认 submit 可选
  16. * @value bind 发生变化时触发
  17. * @value submit 提交时触发
  18. * @property {String} labelPosition = [top|left] label 位置 默认 left 可选
  19. * @value top 顶部显示 label
  20. * @value left 左侧显示 label
  21. * @property {String} labelWidth label 宽度,默认 65px
  22. * @property {String} labelAlign = [left|center|right] label 居中方式 默认 left 可选
  23. * @value left label 左侧显示
  24. * @value center label 居中
  25. * @value right label 右侧对齐
  26. * @property {String} errShowType = [undertext|toast|modal] 校验错误信息提示方式
  27. * @value undertext 错误信息在底部显示
  28. * @value toast 错误信息toast显示
  29. * @value modal 错误信息modal显示
  30. * @event {Function} submit 提交时触发
  31. */
  32. import Vue from 'vue'
  33. Vue.prototype.binddata = function(name, value, formName) {
  34. if (formName) {
  35. this.$refs[formName].setValue(name, value)
  36. } else {
  37. let formVm
  38. for (let i in this.$refs) {
  39. const vm = this.$refs[i]
  40. if (vm && vm.$options && vm.$options.name === 'uniForms') {
  41. formVm = vm
  42. break
  43. }
  44. }
  45. if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性')
  46. formVm.setValue(name, value)
  47. }
  48. }
  49. import Validator from './validate.js'
  50. export default {
  51. name: 'uniForms',
  52. props: {
  53. value: {
  54. type: Object,
  55. default () {
  56. return {}
  57. }
  58. },
  59. // 表单校验规则
  60. rules: {
  61. type: Object,
  62. default () {
  63. return {}
  64. }
  65. },
  66. // 校验触发器方式,默认 关闭
  67. validateTrigger: {
  68. type: String,
  69. default: ''
  70. },
  71. // label 位置,可选值 top/left
  72. labelPosition: {
  73. type: String,
  74. default: 'left'
  75. },
  76. // label 宽度,单位 px
  77. labelWidth: {
  78. type: [String, Number],
  79. default: 65
  80. },
  81. // label 居中方式,可选值 left/center/right
  82. labelAlign: {
  83. type: String,
  84. default: 'left'
  85. },
  86. errShowType: {
  87. type: String,
  88. default: 'undertext'
  89. },
  90. border: {
  91. type: Boolean,
  92. default: false
  93. }
  94. },
  95. data() {
  96. return {
  97. formData: {}
  98. };
  99. },
  100. watch: {
  101. rules(newVal) {
  102. this.init(newVal)
  103. },
  104. trigger(trigger) {
  105. this.formTrigger = trigger
  106. },
  107. },
  108. created() {
  109. let _this = this
  110. this.childrens = []
  111. this.inputChildrens = []
  112. this.checkboxChildrens = []
  113. this.formRules = []
  114. // this.init(this.rules)
  115. },
  116. mounted() {
  117. this.init(this.rules)
  118. },
  119. methods: {
  120. init(formRules) {
  121. // 判断是否有规则
  122. if (Object.keys(formRules).length > 0) {
  123. this.formTrigger = this.trigger
  124. this.formRules = formRules
  125. if (!this.validator) {
  126. this.validator = new Validator(formRules)
  127. }
  128. } else {
  129. return
  130. }
  131. // 判断表单存在那些实例
  132. for (let i in this.value) {
  133. const itemData = this.childrens.find(v => v.name === i)
  134. if (itemData) {
  135. this.formData[i] = this.value[i]
  136. itemData.init()
  137. }
  138. }
  139. // watch 每个属性 ,需要知道具体那个属性发变化
  140. Object.keys(this.value).forEach((key) => {
  141. this.$watch('value.' + key, (newVal) => {
  142. const itemData = this.childrens.find(v => v.name === key)
  143. if (itemData) {
  144. this.formData[key] = this._getValue(key, newVal)
  145. itemData.init()
  146. } else {
  147. this.formData[key] = this.value[key] || null
  148. }
  149. })
  150. })
  151. },
  152. /**
  153. * 设置校验规则
  154. * @param {Object} formRules
  155. */
  156. setRules(formRules) {
  157. this.init(formRules)
  158. },
  159. /**
  160. * 公开给用户使用
  161. * 设置自定义表单组件 value 值
  162. * @param {String} name 字段名称
  163. * @param {String} value 字段值
  164. */
  165. setValue(name, value, callback) {
  166. let example = this.childrens.find(child => child.name === name)
  167. if (!example) return null
  168. value = this._getValue(example.name, value)
  169. this.formData[name] = value
  170. example.val = value
  171. this.$emit('input', Object.assign({}, this.value, this.formData))
  172. return example.triggerCheck(value, callback)
  173. },
  174. /**
  175. * TODO 表单提交, 小程序暂不支持这种用法
  176. * @param {Object} event
  177. */
  178. submitForm(event) {
  179. const value = event.detail.value
  180. return this.validateAll(value || this.formData, 'submit')
  181. },
  182. /**
  183. * 表单重置
  184. * @param {Object} event
  185. */
  186. resetForm(event) {
  187. this.childrens.forEach(item => {
  188. item.errMsg = ''
  189. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  190. if (inputComp) {
  191. inputComp.errMsg = ''
  192. inputComp.$emit('input', inputComp.multiple ? [] : '')
  193. }
  194. })
  195. this.childrens.forEach((item) => {
  196. if (item.name) {
  197. this.formData[item.name] = this._getValue(item.name, '')
  198. }
  199. })
  200. this.$emit('input', this.formData)
  201. this.$emit('reset', event)
  202. },
  203. /**
  204. * 触发表单校验,通过 @validate 获取
  205. * @param {Object} validate
  206. */
  207. validateCheck(validate) {
  208. if (validate === null) validate = null
  209. this.$emit('validate', validate)
  210. },
  211. /**
  212. * 校验所有或者部分表单
  213. */
  214. async validateAll(invalidFields, type, callback) {
  215. this.childrens.forEach(item => {
  216. item.errMsg = ''
  217. })
  218. let promise;
  219. if (!callback && typeof callback !== 'function' && Promise) {
  220. promise = new Promise((resolve, reject) => {
  221. callback = function(valid, invalidFields) {
  222. !valid ? resolve(invalidFields) : reject(valid);
  223. };
  224. });
  225. }
  226. let fieldsValue = {}
  227. let tempInvalidFields = Object.assign({}, invalidFields)
  228. Object.keys(this.formRules).forEach(item => {
  229. const values = this.formRules[item]
  230. const rules = (values && values.rules) || []
  231. let isNoField = false
  232. for (let i = 0; i < rules.length; i++) {
  233. const rule = rules[i]
  234. if (rule.required) {
  235. isNoField = true
  236. break
  237. }
  238. }
  239. // 如果存在 required 才会将内容插入校验对象
  240. if (!isNoField && (!tempInvalidFields[item] && tempInvalidFields[item] !== false)) {
  241. delete tempInvalidFields[item]
  242. }
  243. })
  244. // 循环字段是否存在于校验规则中
  245. for (let i in this.formRules) {
  246. for (let j in tempInvalidFields) {
  247. const index = this.childrens.findIndex(v => v.name === j)
  248. if (i === j && index !== -1) {
  249. fieldsValue[i] = tempInvalidFields[i]
  250. }
  251. }
  252. }
  253. let result = []
  254. let example = null
  255. let newFormData = {}
  256. this.childrens.forEach(v => {
  257. newFormData[v.name] = this._getValue(v.name, invalidFields[v.name])
  258. })
  259. if (this.validator) {
  260. for (let i in fieldsValue) {
  261. // 循环校验,目的是异步校验
  262. const resultData = await this.validator.validateUpdate({
  263. [i]: fieldsValue[i]
  264. }, this.formData)
  265. // 未通过
  266. if (resultData) {
  267. // 获取当前未通过子组件实例
  268. example = this.childrens.find(child => child.name === resultData.key)
  269. // 获取easyInput 组件实例
  270. const inputComp = this.inputChildrens.find(child => child.rename === (example && example.name))
  271. if (inputComp) {
  272. inputComp.errMsg = resultData.errorMessage
  273. }
  274. result.push(resultData)
  275. // 区分触发类型
  276. if (this.errShowType === 'undertext') {
  277. if (example) example.errMsg = resultData.errorMessage
  278. } else {
  279. if (this.errShowType === 'toast') {
  280. uni.showToast({
  281. title: resultData.errorMessage || '校验错误',
  282. icon: 'none'
  283. })
  284. break
  285. } else if (this.errShowType === 'modal') {
  286. uni.showModal({
  287. title: '提示',
  288. content: resultData.errorMessage || '校验错误'
  289. })
  290. break
  291. } else {
  292. if (example) example.errMsg = resultData.errorMessage
  293. }
  294. }
  295. }
  296. }
  297. }
  298. if (Array.isArray(result)) {
  299. if (result.length === 0) result = null
  300. }
  301. if (type === 'submit') {
  302. this.$emit('submit', {
  303. detail: {
  304. value: newFormData,
  305. errors: result
  306. }
  307. })
  308. } else {
  309. this.$emit('validate', result)
  310. }
  311. callback && typeof callback === 'function' && callback(result, newFormData)
  312. if (promise && callback) {
  313. return promise
  314. } else {
  315. return null
  316. }
  317. },
  318. /**
  319. * 外部调用方法
  320. * 手动提交校验表单
  321. * 对整个表单进行校验的方法,参数为一个回调函数。
  322. */
  323. submit(callback) {
  324. // Object.assign(this.formData,formData)
  325. for (let i in this.value) {
  326. const itemData = this.childrens.find(v => v.name === i)
  327. if (itemData) {
  328. this.formData[i] = this._getValue(i, this.value[i])
  329. }
  330. }
  331. return this.validateAll(this.formData, 'submit', callback)
  332. },
  333. /**
  334. * 外部调用方法
  335. * 校验表单
  336. * 对整个表单进行校验的方法,参数为一个回调函数。
  337. */
  338. validate(callback) {
  339. return this.validateAll(this.formData, '', callback)
  340. },
  341. /**
  342. * 部分表单校验
  343. * @param {Object} props
  344. * @param {Object} cb
  345. */
  346. validateField(props, callback) {
  347. props = [].concat(props);
  348. let invalidFields = {}
  349. this.childrens.forEach(item => {
  350. if (props.indexOf(item.name) !== -1) {
  351. invalidFields = Object.assign({}, invalidFields, {
  352. [item.name]: this.formData[item.name]
  353. })
  354. }
  355. })
  356. return this.validateAll(invalidFields, '', callback)
  357. },
  358. /**
  359. * 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
  360. */
  361. resetFields() {
  362. this.resetForm()
  363. },
  364. /**
  365. * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
  366. */
  367. clearValidate(props) {
  368. props = [].concat(props);
  369. this.childrens.forEach(item => {
  370. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  371. if (props.length === 0) {
  372. item.errMsg = ''
  373. if (inputComp) {
  374. inputComp.errMsg = ''
  375. }
  376. } else {
  377. if (props.indexOf(item.name) !== -1) {
  378. item.errMsg = ''
  379. if (inputComp) {
  380. inputComp.errMsg = ''
  381. }
  382. }
  383. }
  384. })
  385. },
  386. /**
  387. * 把 value 转换成指定的类型
  388. * @param {Object} key
  389. * @param {Object} value
  390. */
  391. _getValue(key, value) {
  392. const rules = (this.formRules[key] && this.formRules[key].rules) || []
  393. const isRuleNum = rules.find(val => val.format && this.type_filter(val.format))
  394. const isRuleBool = rules.find(val => val.format && val.format === 'boolean' || val.format === 'bool')
  395. // 输入值为 number
  396. if (isRuleNum) {
  397. value = isNaN(value) ? value : (value === '' || value === null ? null : Number(value))
  398. }
  399. // 简单判断真假值
  400. if (isRuleBool) {
  401. value = !value ? false : true
  402. }
  403. return value
  404. },
  405. /**
  406. * 过滤数字类型
  407. * @param {Object} format
  408. */
  409. type_filter(format) {
  410. return format === 'int' || format === 'double' || format === 'number' || format === 'timestamp'
  411. }
  412. }
  413. }
  414. </script>
  415. <style lang="scss" scoped>
  416. .uni-forms {
  417. // overflow: hidden;
  418. // padding: 10px 15px;
  419. }
  420. .uni-forms--top {
  421. // padding: 10px 15px;
  422. // padding-top: 22px;
  423. }
  424. </style>