Pasas demasiado tiempo haciendo tareas repetitivas al desarrollar con Vue 2.

El truco

// Antes (mal)
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    this.fetchItems();
  },
  methods: {
    fetchItems() {
      axios.get('/api/items')
        .then(response => {
          this.items = response.data;
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};

// Después (bien)
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    this.fetchItems();
  },
  methods: {
    async fetchItems() {
      try {
        this.items = await this.getData('/api/items');
      } catch (error) {
        console.error(error);
      }
    },
    async getData(url) {
      const response = await axios.get(url);
      return response.data;
    }
  }
};

Reutiliza el método getData para centralizar la obtención de datos con Axios. El código es más limpio y te permite manejar cambios futuros en un solo lugar. Este enfoque también reduce el riesgo de errores en casos de uso repetitivo al desarrollar nuevas funcionalidades.

La centralización de las tareas comunes ahorra tiempo y reduce el esfuerzo manual innecesario.