Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import request from '@/utils/request'
- class Errors {
- constructor() {
- this.errors = {}
- }
- has(field) {
- return this.errors.hasOwnProperty(field)
- }
- any() {
- return Object.keys(this.errors).length > 0
- }
- get(field) {
- if (this.errors[field]) {
- return this.errors[field][0]
- }
- }
- record(errors) {
- this.errors = errors
- }
- clear(field) {
- if (field) {
- delete this.errors[field]
- return
- }
- this.errors = {}
- }
- }
- export default class Form {
- constructor(data) {
- this.originalData = data
- for (const field in data) {
- this[field] = data[field]
- }
- this.errors = new Errors()
- this.submiting = false
- }
- data() {
- const data = {}
- for (const property in this.originalData) {
- if (this[property] !== null) {
- data[property] = this[property]
- }
- }
- return data
- }
- reset() {
- for (const field in this.originalData) {
- this[field] = this.originalData[field]
- }
- this.errors.clear()
- }
- post(url) {
- return this.submit('post', url)
- }
- submit(requestType, url) {
- this.submiting = true
- return new Promise((resolve, reject) => {
- request({
- url: url,
- method: requestType,
- data: this.data()
- })
- .then(response => {
- this.submiting = false
- this.onSuccess()
- resolve(response.data)
- })
- .catch(error => {
- this.submiting = false
- this.onFail(error.response.data.error)
- reject(error.response.data.error)
- })
- })
- }
- onSuccess() {
- this.reset()
- }
- onFail(errors) {
- this.errors.record(errors)
- }
- }
Add Comment
Please, Sign In to add comment