Guest User

Untitled

a guest
Sep 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import request from '@/utils/request'
  2.  
  3. class Errors {
  4. constructor() {
  5. this.errors = {}
  6. }
  7. has(field) {
  8. return this.errors.hasOwnProperty(field)
  9. }
  10. any() {
  11. return Object.keys(this.errors).length > 0
  12. }
  13. get(field) {
  14. if (this.errors[field]) {
  15. return this.errors[field][0]
  16. }
  17. }
  18. record(errors) {
  19. this.errors = errors
  20. }
  21. clear(field) {
  22. if (field) {
  23. delete this.errors[field]
  24. return
  25. }
  26. this.errors = {}
  27. }
  28. }
  29.  
  30. export default class Form {
  31. constructor(data) {
  32. this.originalData = data
  33. for (const field in data) {
  34. this[field] = data[field]
  35. }
  36. this.errors = new Errors()
  37. this.submiting = false
  38. }
  39. data() {
  40. const data = {}
  41. for (const property in this.originalData) {
  42. if (this[property] !== null) {
  43. data[property] = this[property]
  44. }
  45. }
  46. return data
  47. }
  48. reset() {
  49. for (const field in this.originalData) {
  50. this[field] = this.originalData[field]
  51. }
  52. this.errors.clear()
  53. }
  54. post(url) {
  55. return this.submit('post', url)
  56. }
  57. submit(requestType, url) {
  58. this.submiting = true
  59. return new Promise((resolve, reject) => {
  60. request({
  61. url: url,
  62. method: requestType,
  63. data: this.data()
  64. })
  65. .then(response => {
  66. this.submiting = false
  67. this.onSuccess()
  68. resolve(response.data)
  69. })
  70. .catch(error => {
  71. this.submiting = false
  72. this.onFail(error.response.data.error)
  73. reject(error.response.data.error)
  74. })
  75. })
  76. }
  77. onSuccess() {
  78. this.reset()
  79. }
  80. onFail(errors) {
  81. this.errors.record(errors)
  82. }
  83. }
Add Comment
Please, Sign In to add comment