D
D
Dos2019-11-08 03:15:48
Vue.js
Dos, 2019-11-08 03:15:48

How to refactor work with errors?

Hey! There is a repeating code from view to view.

export default {
    data() {
      return {
        form: {
          name: null,
          dateFrom: null,
        },
        error: null,
        errors: []
      }
    },
    methods: {
      create() {
        this.error = null;
        this.errors = [];
        axios
          .post('/events/create', this.form)
          .then(() => {
            this.$router.push({name: 'events'});
          })
          .catch(error => {
            if (error.response) {
              if (error.response.data.error) {
                this.error = error.response.data.error;
              } else if (error.response.data.errors) {
                this.errors = error.response.data.errors;
              }
            } else {
             /* console.log(error.message);*/
            }
          });
      }
    }
  }

The bottom line is that after axios request to api, validation errors or one error from Exeption to php are obtained.
If the server returns an error, then we process it
.catch(error => {
            if (error.response) {
              if (error.response.data.error) { //если ошибка от Exeption
                this.error = error.response.data.error;
              } else if (error.response.data.errors) { // Если ошибки валидации формы
                this.errors = error.response.data.errors;
              }
            } else {
             /* console.log(error.message);*/
            }
          });

In addition, we are forced to record this data in two places:
create() {
        this.error = null;
        this.errors = [];
...}

data() {
      return {
       .....
        error: null,
        errors: []
      }
    },

1. How can it be shortened?
2. How can this be taken out of all views somewhere in a separate place where vue will handle validation and exeption errors?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question