Я хочу использовать метод API извлечения для инициализации состояния магазина, но почему он не работает? - PullRequest
0 голосов
/ 06 июня 2018

В моем store.js, у меня есть состояние user_data, его начальный метод fetch_user_data:

export default new Vuex.Store({
  state: {
    user_data: util.fetch_user_data('username')
    ...
  }

в util.js:

util.fetch_user_data = function(username){
   Lml_http('get', Api_urls.productconfig_common.user_data(username), null, response => {

    return response.data  // there get the data, in the debugger shows it.
  }, error => {

  })
}

Нокогда я использую state user_data, это undefined.


РЕДАКТИРОВАТЬ-1

Я хочу в store.jsиспользовать метод fetch_util для извлечения данных и зафиксировать код state.

EDIT-2

my lml_http ниже:

var lml_http = function (method, url, params, success_cb, error_cb, multipart_formdata=undefined) {

  var format_to_form_data = function(data){

    let formData = new FormData()
    for (let item in data) {
      formData.append(item, data[item])
    }
    return formData
  }

  var lowercase_method = method.toLowerCase()

  var formated_params = params

  var header_config = null

  if (multipart_formdata) {
    header_config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }

    formated_params = format_to_form_data(formated_params)
  }

  if(lowercase_method === "get") {

    formated_params = {params: formated_params}

    if (!header_config) {

      Axios.get(url, formated_params).then(response => {
        success_cb(response)
        return
      }).catch(response => {
        error_cb(response)
        return
      })
    } else {
      Axios.get(url, format_to_form_data(formated_params), header_config).then(response => {
        success_cb(response)
        return
      }).catch(response => {
        error_cb(response)
        return
      })

    }

    return
  }
  else {


    if(!header_config) {

      Axios[method](url, formated_params).then(response => {
        success_cb(response)
      }).catch(response => {
        error_cb(response)
      })
      return
    }else {
      Axios[method](url, formated_params, header_config).then(response => {
        success_cb(response)
      }).catch( response => {
        error_cb(response)
      })
      return
    }

  }

}

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Просто создайте действие для извлечения пользовательских данных следующим образом:

export default new Vuex.Store({
  state: {
    user_data: null
  },
  mutations: {
    setUserData(state, data) {
      state.user_data = data;
    }
  },
  actions: {
    fetchUserData({ commit }, username) {
      Lml_http(
        "get",
        Api_urls.productconfig_common.user_data(username),
        null,
        response => {
          commit("setUserData", response.data);
        },
        error => {}
      );
    }
  }
});

Затем отправьте это действие в created() хук экземпляра theroot vue

//main.js

new Vue({
  el: "#app",
  store,
  render: h => h(App),
  created() {
    this.$store.dispatch("fetchUserData", "username");
  }
});

`

Редактировать:

Axios возвращает Promise по умолчанию.Поэтому в lml_http возвратите вызовы Axios, как показано ниже:

var lml_http = function(
  method,
  url,
  params,
  success_cb,
  error_cb,
  multipart_formdata = undefined
) {
  var format_to_form_data = function(data) {
    let formData = new FormData();
    for (let item in data) {
      formData.append(item, data[item]);
    }
    return formData;
  };

  var lowercase_method = method.toLowerCase();

  var formated_params = params;

  var header_config = null;

  if (multipart_formdata) {
    header_config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };

    formated_params = format_to_form_data(formated_params);
  }

  if (lowercase_method === "get") {
    formated_params = { params: formated_params };

    if (!header_config) {
      return Axios.get(url, formated_params)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    } else {
      return Axios.get(url, format_to_form_data(formated_params), header_config)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    }
  } else {
    if (!header_config) {
      return Axios[method](url, formated_params)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    } else {
      return Axios[method](url, formated_params, header_config)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    }
  }
};

Также добавьте оператор возврата в utils.js

util.fetch_user_data = function(username){
   return Lml_http('get', Api_urls.productconfig_common.user_data(username), null, response => {

    return response.data  // there get the data, in the debugger shows it.
  }, error => {

  })
}

Теперь в вашем действии fetchUserData

fetchUserData({ commit }) {
    util.fetch_user_data('username').then((
      commit("setUserData", response.data);
    });
}

В main.js отправьте действие без какой-либо полезной нагрузки

// main.js

new Vue({
  el: "#app",
  store,
  render: h => h(App),
  created() {
    this.$store.dispatch("fetchUserData", "username");
  }
});
0 голосов
/ 06 июня 2018

Поскольку API выборки является асинхронным, он возвращает обещание, а не данные ответа.Я думаю, вы можете попробовать что-то вроде:

const store = new Vuex.Store({
  state: {
  user_data: null,
  ...
};

util.fetch_user_data('username')
  .then(user => store.user_data = user);

export default store;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...