uni-forms.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. import Vue from 'vue'
  11. import Validator from './validate.js'
  12. Vue.prototype.binddata = function(name, value, formName) {
  13. if (formName) {
  14. this.$refs[formName].setValue(name, value)
  15. } else {
  16. let formVm
  17. for (let i in this.$refs) {
  18. const vm = this.$refs[i]
  19. if (vm && vm.$options && vm.$options.name === 'uniForms') {
  20. formVm = vm
  21. break
  22. }
  23. }
  24. if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性')
  25. formVm.setValue(name, value)
  26. }
  27. }
  28. /**
  29. * Forms 表单
  30. * @description 由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据
  31. * @tutorial https://ext.dcloud.net.cn/plugin?id=2773
  32. * @property {Object} rules 表单校验规则
  33. * @property {String} validateTrigger = [bind|submit] 校验触发器方式 默认 submit 可选
  34. * @value bind 发生变化时触发
  35. * @value submit 提交时触发
  36. * @property {String} labelPosition = [top|left] label 位置 默认 left 可选
  37. * @value top 顶部显示 label
  38. * @value left 左侧显示 label
  39. * @property {String} labelWidth label 宽度,默认 65px
  40. * @property {String} labelAlign = [left|center|right] label 居中方式 默认 left 可选
  41. * @value left label 左侧显示
  42. * @value center label 居中
  43. * @value right label 右侧对齐
  44. * @property {String} errShowType = [undertext|toast|modal] 校验错误信息提示方式
  45. * @value undertext 错误信息在底部显示
  46. * @value toast 错误信息toast显示
  47. * @value modal 错误信息modal显示
  48. * @event {Function} submit 提交时触发
  49. */
  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 &&
  241. ((tempInvalidFields[item] === undefined ||
  242. tempInvalidFields[item] === '') &&
  243. tempInvalidFields[item] !== false
  244. )) {
  245. delete tempInvalidFields[item]
  246. }
  247. })
  248. // 循环字段是否存在于校验规则中
  249. for (let i in this.formRules) {
  250. for (let j in tempInvalidFields) {
  251. const index = this.childrens.findIndex(v => v.name === j)
  252. if (i === j && index !== -1) {
  253. fieldsValue[i] = tempInvalidFields[i]
  254. }
  255. }
  256. }
  257. let result = []
  258. let example = null
  259. let newFormData = {}
  260. this.childrens.forEach(v => {
  261. newFormData[v.name] = this._getValue(v.name, invalidFields[v.name])
  262. })
  263. if (this.validator) {
  264. for (let i in fieldsValue) {
  265. // 循环校验,目的是异步校验
  266. const resultData = await this.validator.validateUpdate({
  267. [i]: fieldsValue[i]
  268. }, this.formData)
  269. // 未通过
  270. if (resultData) {
  271. // 获取当前未通过子组件实例
  272. example = this.childrens.find(child => child.name === resultData.key)
  273. // 获取easyInput 组件实例
  274. const inputComp = this.inputChildrens.find(child => child.rename === (example && example
  275. .name))
  276. if (inputComp) {
  277. inputComp.errMsg = resultData.errorMessage
  278. }
  279. result.push(resultData)
  280. // 区分触发类型
  281. if (this.errShowType === 'undertext') {
  282. if (example) example.errMsg = resultData.errorMessage
  283. } else {
  284. if (this.errShowType === 'toast') {
  285. uni.showToast({
  286. title: resultData.errorMessage || '校验错误',
  287. icon: 'none'
  288. })
  289. break
  290. } else if (this.errShowType === 'modal') {
  291. uni.showModal({
  292. title: '提示',
  293. content: resultData.errorMessage || '校验错误'
  294. })
  295. break
  296. } else {
  297. if (example) example.errMsg = resultData.errorMessage
  298. }
  299. }
  300. }
  301. }
  302. }
  303. if (Array.isArray(result)) {
  304. if (result.length === 0) result = null
  305. }
  306. if (type === 'submit') {
  307. this.$emit('submit', {
  308. detail: {
  309. value: newFormData,
  310. errors: result
  311. }
  312. })
  313. } else {
  314. this.$emit('validate', result)
  315. }
  316. callback && typeof callback === 'function' && callback(result, newFormData)
  317. if (promise && callback) {
  318. return promise
  319. } else {
  320. return null
  321. }
  322. },
  323. /**
  324. * 外部调用方法
  325. * 手动提交校验表单
  326. * 对整个表单进行校验的方法,参数为一个回调函数。
  327. */
  328. submit(callback) {
  329. // Object.assign(this.formData,formData)
  330. for (let i in this.value) {
  331. const itemData = this.childrens.find(v => v.name === i)
  332. if (itemData) {
  333. if (this.formData[i] === undefined) {
  334. this.formData[i] = this._getValue(i, this.value[i])
  335. }
  336. }
  337. }
  338. return this.validateAll(this.formData, 'submit', callback)
  339. },
  340. /**
  341. * 外部调用方法
  342. * 校验表单
  343. * 对整个表单进行校验的方法,参数为一个回调函数。
  344. */
  345. validate(callback) {
  346. return this.validateAll(this.formData, '', callback)
  347. },
  348. /**
  349. * 部分表单校验
  350. * @param {Object} props
  351. * @param {Object} cb
  352. */
  353. validateField(props, callback) {
  354. props = [].concat(props);
  355. let invalidFields = {}
  356. this.childrens.forEach(item => {
  357. if (props.indexOf(item.name) !== -1) {
  358. invalidFields = Object.assign({}, invalidFields, {
  359. [item.name]: this.formData[item.name]
  360. })
  361. }
  362. })
  363. return this.validateAll(invalidFields, '', callback)
  364. },
  365. /**
  366. * 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
  367. */
  368. resetFields() {
  369. this.resetForm()
  370. },
  371. /**
  372. * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
  373. */
  374. clearValidate(props) {
  375. props = [].concat(props);
  376. this.childrens.forEach(item => {
  377. const inputComp = this.inputChildrens.find(child => child.rename === item.name)
  378. if (props.length === 0) {
  379. item.errMsg = ''
  380. if (inputComp) {
  381. inputComp.errMsg = ''
  382. }
  383. } else {
  384. if (props.indexOf(item.name) !== -1) {
  385. item.errMsg = ''
  386. if (inputComp) {
  387. inputComp.errMsg = ''
  388. }
  389. }
  390. }
  391. })
  392. },
  393. /**
  394. * 把 value 转换成指定的类型
  395. * @param {Object} key
  396. * @param {Object} value
  397. */
  398. _getValue(key, value) {
  399. const rules = (this.formRules[key] && this.formRules[key].rules) || []
  400. const isRuleNum = rules.find(val => val.format && this.type_filter(val.format))
  401. const isRuleBool = rules.find(val => val.format && val.format === 'boolean' || val.format === 'bool')
  402. // 输入值为 number
  403. if (isRuleNum) {
  404. value = isNaN(value) ? value : (value === '' || value === null ? null : Number(value))
  405. }
  406. // 简单判断真假值
  407. if (isRuleBool) {
  408. value = !value ? false : true
  409. }
  410. return value
  411. },
  412. /**
  413. * 过滤数字类型
  414. * @param {Object} format
  415. */
  416. type_filter(format) {
  417. return format === 'int' || format === 'double' || format === 'number' || format === 'timestamp'
  418. }
  419. }
  420. }
  421. </script>
  422. <style lang="scss" scoped>
  423. .uni-forms {
  424. // overflow: hidden;
  425. // padding: 10px 15px;
  426. }
  427. .uni-forms--top {
  428. // padding: 10px 15px;
  429. // padding-top: 22px;
  430. }
  431. </style>