[Vue]使用axios实现ajax请求

1.定义myAjax

export const myAjax=function createHttpClient(ajaxConfig) {
  let httpClient = null;
  if (ajaxConfig) {
    httpClient = axios.create(ajaxConfig);
    httpClient.interceptors.request.use(...);
    httpClient.interceptors.response.use(...);
  else {
    httpClient = axios.create()
  }
  return httpClient;
}

 axios:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

详细可参考官方文档:https://www.kancloud.cn/yunye/axios/234845

2.生成ajaxMixin

export const ajaxMixin = {
  created() {
    const ajaxConfig = this.$options.myAjaxConfig
    this.$_myAjax = myAjax(ajaxConfig)
  },
}
$options:当前 Vue 实例的初始化选项(在选项中包含自定义属性(myAjaxConfig)

3.在new Vue实例化前混入ajaxMixin
Vue.mixin(ajaxMixin)

new Vue({
  router,
  store,
  i18n,
  render: h => h(App),
}).$mount('#app')
Vue.mixin( mixin ):全局注册一个混入,影响注册之后所有创建的每个 Vue 实例,向组件注入自定义的行为。

4.在具体模块中自定义myAjaxConfig,以及调用this.$_myAjax请求后台数据
export default {
  ...
  myAjaxConfig: {
    showSpinner: true,
    baseURL: '/api/F64/',
  },
  methods: {  
    // 从服务器加载画面所需数据
    loadAllData(eigyousyoIdValue) {
      return this.$_myAjax
        .post(
          'GetGoodsInfo',
          {},
          {
            headers: {
              eigyousyoId: eigyousyoIdValue,
            },
          }
        )
   },
...
}

 详细使用方式见:https://www.cnblogs.com/vickylinj/p/10888698.html




posted @ 2018-08-26 17:57  vickylinj  阅读(263)  评论(0编辑  收藏  举报