uni-forms.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. value: {
  108. handler(newVal) {
  109. if (this.isChildEdit) {
  110. this.isChildEdit = false
  111. return
  112. }
  113. this.childrens.forEach((item) => {
  114. if (item.name) {
  115. const formDataValue = newVal.hasOwnProperty(item.name) ? newVal[item.name] : null
  116. this.formData[item.name] = this._getValue(item, formDataValue)
  117. }
  118. })
  119. },
  120. deep: true
  121. }
  122. },
  123. created() {
  124. let _this = this
  125. this.childrens = []
  126. this.inputChildrens = []
  127. this.checkboxChildrens = []
  128. this.formRules = []
  129. this.init(this.rules)
  130. },
  131. methods: {
  132. init(formRules) {
  133. if (Object.keys(formRules).length > 0) {
  134. this.formTrigger = this.trigger
  135. this.formRules = formRules
  136. if (!this.validator) {
  137. this.validator = new Validator(formRules)
  138. }
  139. }
  140. this.childrens.forEach((item) => {
  141. item.init()
  142. })
  143. },
  144. /**
  145. * 设置校验规则
  146. * @param {Object} formRules
  147. */
  148. setRules(formRules) {
  149. this.init(formRules)
  150. },
  151. /**
  152. * 公开给用户使用
  153. * 设置自定义表单组件 value 值
  154. * @param {String} name 字段名称
  155. * @param {String} value 字段值
  156. */
  157. setValue(name, value, callback) {
  158. let example = this.childrens.find(child => child.name === name)
  159. if (!example) return null
  160. this.isChildEdit = true
  161. value = this._getValue(example, value)
  162. this.formData[name] = value
  163. example.val = value
  164. this.$emit('input', Object.assign({}, this.value, this.formData))
  165. return example.triggerCheck(value, callback)
  166. },
  167. /**
  168. * TODO 表单提交, 小程序暂不支持这种用法
  169. * @param {Object} event
  170. */
  171. submitForm(event) {
  172. const value = event.detail.value
  173. return this.validateAll(value || this.formData, 'submit')
  174. },
  175. /**
  176. * 表单重置
  177. * @param {Object} event
  178. */
  179. resetForm(event) {
  180. this.childrens.forEach(item => {
  181. item.errMsg = ''
  182. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  183. if (inputComp) {
  184. inputComp.errMsg = ''
  185. inputComp.$emit('input', inputComp.multiple?[]:'')
  186. }
  187. })
  188. this.isChildEdit = true
  189. this.childrens.forEach((item) => {
  190. if (item.name) {
  191. this.formData[item.name] = this._getValue(item, '')
  192. }
  193. })
  194. this.$emit('input', this.formData)
  195. this.$emit('reset', event)
  196. },
  197. /**
  198. * 触发表单校验,通过 @validate 获取
  199. * @param {Object} validate
  200. */
  201. validateCheck(validate) {
  202. if (validate === null) validate = null
  203. this.$emit('validate', validate)
  204. },
  205. /**
  206. * 校验所有或者部分表单
  207. */
  208. async validateAll(invalidFields, type, callback) {
  209. this.childrens.forEach(item => {
  210. item.errMsg = ''
  211. })
  212. let promise;
  213. if (!callback && typeof callback !== 'function' && Promise) {
  214. promise = new Promise((resolve, reject) => {
  215. callback = function(valid, invalidFields) {
  216. !valid ? resolve(invalidFields) : reject(valid);
  217. };
  218. });
  219. }
  220. let fieldsValue = {}
  221. let tempInvalidFields = Object.assign({}, invalidFields)
  222. Object.keys(this.formRules).forEach(item => {
  223. const values = this.formRules[item]
  224. const rules = (values && values.rules) || []
  225. let isNoField = false
  226. for (let i = 0; i < rules.length; i++) {
  227. const rule = rules[i]
  228. if (rule.required) {
  229. isNoField = true
  230. break
  231. }
  232. }
  233. // 如果存在 required 才会将内容插入校验对象
  234. if (!isNoField && (!tempInvalidFields[item] && tempInvalidFields[item] !== false)) {
  235. delete tempInvalidFields[item]
  236. }
  237. })
  238. // 循环字段是否存在于校验规则中
  239. for (let i in this.formRules) {
  240. for (let j in tempInvalidFields) {
  241. if (i === j) {
  242. fieldsValue[i] = tempInvalidFields[i]
  243. }
  244. }
  245. }
  246. let result = []
  247. let example = null
  248. if (this.validator) {
  249. for (let i in fieldsValue) {
  250. const resultData = await this.validator.validateUpdate({
  251. [i]: fieldsValue[i]
  252. }, this.formData)
  253. if (resultData) {
  254. example = this.childrens.find(child => child.name === resultData.key)
  255. const inputComp = this.inputChildrens.find(child => child.rename === example.name)
  256. if (inputComp) {
  257. inputComp.errMsg = resultData.errorMessage
  258. }
  259. result.push(resultData)
  260. if (this.errShowType === 'undertext') {
  261. if (example) example.errMsg = resultData.errorMessage
  262. } else {
  263. if (this.errShowType === 'toast') {
  264. uni.showToast({
  265. title: resultData.errorMessage || '校验错误',
  266. icon: 'none'
  267. })
  268. break
  269. } else if (this.errShowType === 'modal') {
  270. uni.showModal({
  271. title: '提示',
  272. content: resultData.errorMessage || '校验错误'
  273. })
  274. break
  275. } else {
  276. if (example) example.errMsg = resultData.errorMessage
  277. }
  278. }
  279. }
  280. }
  281. }
  282. if (Array.isArray(result)) {
  283. if (result.length === 0) result = null
  284. }
  285. if (type === 'submit') {
  286. this.$emit('submit', {
  287. detail: {
  288. value: invalidFields,
  289. errors: result
  290. }
  291. })
  292. } else {
  293. this.$emit('validate', result)
  294. }
  295. callback && typeof callback === 'function' && callback(result, invalidFields)
  296. if (promise && callback) {
  297. return promise
  298. } else {
  299. return null
  300. }
  301. },
  302. /**
  303. * 外部调用方法
  304. * 手动提交校验表单
  305. * 对整个表单进行校验的方法,参数为一个回调函数。
  306. */
  307. submit(callback) {
  308. // Object.assign(this.formData,formData)
  309. return this.validateAll(this.formData, 'submit', callback)
  310. },
  311. /**
  312. * 外部调用方法
  313. * 校验表单
  314. * 对整个表单进行校验的方法,参数为一个回调函数。
  315. */
  316. validate(callback) {
  317. return this.validateAll(this.formData, '', callback)
  318. },
  319. /**
  320. * 部分表单校验
  321. * @param {Object} props
  322. * @param {Object} cb
  323. */
  324. validateField(props, callback) {
  325. props = [].concat(props);
  326. let invalidFields = {}
  327. this.childrens.forEach(item => {
  328. // item.parentVal((val, name) => {
  329. if (props.indexOf(item.name) !== -1) {
  330. invalidFields = Object.assign({}, invalidFields, {
  331. [item.name]: this.formData[item.name]
  332. })
  333. }
  334. // })
  335. })
  336. return this.validateAll(invalidFields, '', callback)
  337. },
  338. /**
  339. * 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
  340. */
  341. resetFields() {
  342. this.resetForm()
  343. },
  344. /**
  345. * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
  346. */
  347. clearValidate(props) {
  348. props = [].concat(props);
  349. this.childrens.forEach(item => {
  350. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  351. if (props.length === 0) {
  352. item.errMsg = ''
  353. if (inputComp) {
  354. inputComp.errMsg = ''
  355. }
  356. } else {
  357. if (props.indexOf(item.name) !== -1) {
  358. item.errMsg = ''
  359. if (inputComp) {
  360. inputComp.errMsg = ''
  361. }
  362. }
  363. }
  364. })
  365. },
  366. // 把 value 转换成指定的类型
  367. _getValue(item, value) {
  368. const rules = item.formRules.rules || []
  369. const isRuleNum = rules.find(val => val.format && this.type_filter(val.format))
  370. const isRuleBool = rules.find(val => val.format && val.format === 'boolean' || val.format === 'bool')
  371. // 输入值为 number
  372. if (isRuleNum) {
  373. value = value === '' || value === null ? null : Number(value)
  374. }
  375. // 简单判断真假值
  376. if (isRuleBool) {
  377. value = !value ? false : true
  378. }
  379. return value
  380. },
  381. // 过滤数字类型
  382. type_filter(format) {
  383. return format === 'int' || format === 'double' || format === 'number'
  384. }
  385. }
  386. }
  387. </script>
  388. <style lang="scss" scoped>
  389. .uni-forms {
  390. overflow: hidden;
  391. // padding: 10px 15px;
  392. // background-color: #fff;
  393. }
  394. .uni-forms--top {
  395. padding: 10px 15px;
  396. // padding-top: 22px;
  397. }
  398. </style>