如何编写完美的vue.js操作以从服务器获取数据并进行适当的错误处理?

时间:2017-07-10 11:47:20

标签: vue.js vuex

export const fetchEnvironmentsData = ({ commit }, params) => {
    Vue.http.get('/environments', { params })
        .then(response => response.json())
        .then(data => {
            if (data) {
                commit('mutateUpdateEnvironmentData', data);
            }
        }).catch(function(error) {
            alert('Could not load data, Please try again later');
        });
};

如何处理内部服务器错误并从服务器清空响应?

1 个答案:

答案 0 :(得分:0)

const error = () => alert('Could not load data, Please try again later');

Vue.http.get('/environments', { params })
  .then(response => {
    const data = response.json();
    if (data) {
      commit('mutateUpdateEnvironmentData', data);
    } else {
      error();
    }
  }, error);

Vue.http.get('/environments', { params })
  .then(response => response.json(), () => null)
  .then(data => {
    if (data) {
      commit('mutateUpdateEnvironmentData', data);
    } else {
      alert('Could not load data, Please try again later');
    }
  });