uni-forms.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. if (i === j) {
  248. fieldsValue[i] = tempInvalidFields[i]
  249. }
  250. }
  251. }
  252. let result = []
  253. let example = null
  254. let newFormData = {}
  255. this.childrens.forEach(v => {
  256. newFormData[v.name] = this._getValue(v.name, invalidFields[v.name])
  257. })
  258. if (this.validator) {
  259. for (let i in fieldsValue) {
  260. // 循环校验,目的是异步校验
  261. const resultData = await this.validator.validateUpdate({
  262. [i]: fieldsValue[i]
  263. }, this.formData)
  264. // 未通过
  265. if (resultData) {
  266. // 获取当前未通过子组件实例
  267. example = this.childrens.find(child => child.name === resultData.key)
  268. // 获取easyInput 组件实例
  269. const inputComp = this.inputChildrens.find(child => child.rename === (example && example.name))
  270. if (inputComp) {
  271. inputComp.errMsg = resultData.errorMessage
  272. }
  273. result.push(resultData)
  274. // 区分触发类型
  275. if (this.errShowType === 'undertext') {
  276. if (example) example.errMsg = resultData.errorMessage
  277. } else {
  278. if (this.errShowType === 'toast') {
  279. uni.showToast({
  280. title: resultData.errorMessage || '校验错误',
  281. icon: 'none'
  282. })
  283. break
  284. } else if (this.errShowType === 'modal') {
  285. uni.showModal({
  286. title: '提示',
  287. content: resultData.errorMessage || '校验错误'
  288. })
  289. break
  290. } else {
  291. if (example) example.errMsg = resultData.errorMessage
  292. }
  293. }
  294. }
  295. }
  296. }
  297. if (Array.isArray(result)) {
  298. if (result.length === 0) result = null
  299. }
  300. if (type === 'submit') {
  301. this.$emit('submit', {
  302. detail: {
  303. value: newFormData,
  304. errors: result
  305. }
  306. })
  307. } else {
  308. this.$emit('validate', result)
  309. }
  310. callback && typeof callback === 'function' && callback(result, newFormData)
  311. if (promise && callback) {
  312. return promise
  313. } else {
  314. return null
  315. }
  316. },
  317. /**
  318. * 外部调用方法
  319. * 手动提交校验表单
  320. * 对整个表单进行校验的方法,参数为一个回调函数。
  321. */
  322. submit(callback) {
  323. // Object.assign(this.formData,formData)
  324. return this.validateAll(this.formData, 'submit', callback)
  325. },
  326. /**
  327. * 外部调用方法
  328. * 校验表单
  329. * 对整个表单进行校验的方法,参数为一个回调函数。
  330. */
  331. validate(callback) {
  332. return this.validateAll(this.formData, '', callback)
  333. },
  334. /**
  335. * 部分表单校验
  336. * @param {Object} props
  337. * @param {Object} cb
  338. */
  339. validateField(props, callback) {
  340. props = [].concat(props);
  341. let invalidFields = {}
  342. this.childrens.forEach(item => {
  343. if (props.indexOf(item.name) !== -1) {
  344. invalidFields = Object.assign({}, invalidFields, {
  345. [item.name]: this.formData[item.name]
  346. })
  347. }
  348. })
  349. return this.validateAll(invalidFields, '', callback)
  350. },
  351. /**
  352. * 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
  353. */
  354. resetFields() {
  355. this.resetForm()
  356. },
  357. /**
  358. * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
  359. */
  360. clearValidate(props) {
  361. props = [].concat(props);
  362. this.childrens.forEach(item => {
  363. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  364. if (props.length === 0) {
  365. item.errMsg = ''
  366. if (inputComp) {
  367. inputComp.errMsg = ''
  368. }
  369. } else {
  370. if (props.indexOf(item.name) !== -1) {
  371. item.errMsg = ''
  372. if (inputComp) {
  373. inputComp.errMsg = ''
  374. }
  375. }
  376. }
  377. })
  378. },
  379. /**
  380. * 把 value 转换成指定的类型
  381. * @param {Object} key
  382. * @param {Object} value
  383. */
  384. _getValue(key, value) {
  385. const rules = (this.formRules[key] && this.formRules[key].rules) || []
  386. const isRuleNum = rules.find(val => val.format && this.type_filter(val.format))
  387. const isRuleBool = rules.find(val => val.format && val.format === 'boolean' || val.format === 'bool')
  388. // 输入值为 number
  389. if (isRuleNum) {
  390. value = isNaN(value) ? value : (value === '' || value === null ? null : Number(value))
  391. }
  392. // 简单判断真假值
  393. if (isRuleBool) {
  394. value = !value ? false : true
  395. }
  396. return value
  397. },
  398. /**
  399. * 过滤数字类型
  400. * @param {Object} format
  401. */
  402. type_filter(format) {
  403. return format === 'int' || format === 'double' || format === 'number' || format === 'timestamp'
  404. }
  405. }
  406. }
  407. </script>
  408. <style scoped>
  409. .uni-forms--top {
  410. padding: 10px 15px;
  411. }
  412. </style>