vue开发公共模块封装(http)

本文主要分享基于vue的移动端ui框架vux简单封装Axios作为我们项目的公共http模块。代码如下:

import Vue from 'vue';
import Axios from 'axios';
import { Promise } from 'es6-promise';
import user from '../store/modules/user'
import server from '../config/hostConfig'

Axios.defaults.timeout = 30000; // 1分钟
Axios.defaults.baseURL = server.target; 

Axios.interceptors.request.use(function(config) {
  // Do something before request is sent 
  //change method for get
  /*if(process.env.NODE_ENV == 'development'){
      config['method'] = 'GET';
      console.log(config)
  }*/
  if(config['MSG']){
    Vue.prototype.$showLoading(config['MSG']);
  }else{
    Vue.prototype.$showLoading();
  }
  if(user.state.token){//用户登录时每次请求将token放入请求头中
    config.headers["token"] = user.state.token;
  }

  if (config['Content-Type'] === 'application/x-www-form-urlencoded;') {//默认发application/json请求,如果application/x-www-form-urlencoded;需要使用transformRequest对参数进行处理
    /*config['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';*/
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    config['transformRequest'] = function(obj) {
      var str = [];
      for (var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      return str.join("&")
    };
  }
  //config.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

  return config;
}, function(error) {
  // Do something with request error 
  Vue.$vux.loading.hide()
  return Promise.reject(error);
});

Axios.interceptors.response.use(
  response => {
    Vue.$vux.loading.hide();
    return response.data;
  },
  error => {
    Vue.$vux.loading.hide();
    if (error.response) {
      switch (error.response.status) {
        case 404:
          Vue.prototype.$alert("404未找到请求的资源");
          break;
        default:
          Vue.prototype.$alert('网络错误');
      }
    } else if (error instanceof Error) {
      console.error(error.message);
    } else {
      Vue.prototype.$alert(error.returnMsg);
    }

    return Promise.reject(error.response.data);
  });

export default Vue.prototype.$http = Axios;

上述代码把http扩展到了vue的原型中,然后我们便可以在组件中方便的使用http,比如:

mobileLogin() {
      let self = this;
      let param = {
        mobile: this.mobile,
        password: this.mobilePw
      }
      self.$http.post('/api/mobile/general/login', param).then((result) => {
          if (result.success) {
            self.USER_SIGNIN({
              token: result.data.token,
              accountInfo: result.data.accountInfo,
              nsrInfo: result.data.nsrInfo
            });
            self.$router.push({
              name: 'chooseIdentity',
              params: {
                isFromLogin: true
              }
            }); //isFromLogin  1代表从login路由
          } else {
            self.$alert(result.message);
          }
          /* return result*/
        })
    }

这样的话我们使用起来是不是方便了很多?嘿嘿,更多axios的用法请参考axios用法
关于vux的用法请参考:vux用法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue公共组件库封装,可以将常用组件封装成一个独立的组件库,供团队内部使用,提高开发效率和代码复用率。以下是一些步骤: 1. 创建一个Vue项目,用于打包组件库。 2. 在src目录下创建一个components文件夹,用于存放组件。 3. 创建一个main.js文件,用于注册所有组件,并导出一个install方法。 4. 在package.json中添加打包命令,如:"build": "vue-cli-service build --target lib --name my-components src/main.js"。 5. 在组件中引入所需的Vue和其他库,如lodash等。 6. 编写组件,可以使用Vue的单文件组件或者普通的JS组件。 7. 在main.js中注册组件,并导出一个install方法,如下: ``` import MyComponent from './components/MyComponent.vue'; const components = [ MyComponent, // 其他组件 ]; const install = function(Vue) { if (install.installed) return; install.installed = true; components.forEach(component => { Vue.component(component.name, component); }); }; if (typeof window !== 'undefined' && window.Vue) { install(window.Vue); } export default { install, MyComponent // 其他组件 }; ``` 8. 执行npm run build命令,将组件库打包成一个umd模块,可以使用script标签或者import语句引入使用。 9. 在其他项目中引入组件库,并使用其中的组件,如下: ``` import MyComponents from 'my-components'; import 'my-components/dist/my-components.css'; Vue.use(MyComponents); // 使用组件 <template> <my-component></my-component> </template> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值