vue封装axios

第一步:在src目录下建新文件夹:api,然后在此文件夹下分别建两个js文件:

第二步:在刚刚新建的axios.js里面配置axios的请求拦截

import axios from 'axios'
// 请求超时时间
axios.defaults.timeout = 1000 * 10;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// 设置公共url
//axios.defaults.baseURL = 'http://127.0.0.1:7001'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  console.log(config);
  // 在发送请求之前做些什么
  return config;
}, function (error) {
  console.log(error);
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  console.log(response);
  // 对响应数据做点什么
  return response;
}, function (error) {
  console.log(error);
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default axios

第三步:在index.js里集中写项目需要的接口请求 

import axios from './axios'
const demo = {
    eggDemo() {
        return axios.get(`/api/role` );
    },
    eggDemo1() {
        return axios.get(`/api/role1` );
    }
}

export default demo;

第四步:把汇总了所有接口的index.js引入到main.js里,并挂载到vue原型上:

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import demo from './api/index'

Vue.config.productionTip = false
Vue.prototype.$axios = axios;  //没封装接口使用
Vue.prototype.$api = demo;//封装接口使用

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

第五步:页面使用

<template>
  <div class="hello">
    <div class="show_data">
      <button @click="clickShowData">加载数据</button>
      <div class="show_box">{{ data }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
        data: ''
    }
  },
  methods: {
    clickShowData() {
      //$api在main.js里已经引入到vue的原型上,不需要在引入就可以通过this.$api直接使用
      this.$api.eggDemo().then(res => {
          this.data = res;
      }).catch(err => {
          this.data = err;
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值