Vue封装Axios

在vue脚手架中需要封装axios来达到更好使用axios的目的

比如 token 的鉴权,错误处理等

 首先我们要在 src目录下创建一个plugins 文件夹

这个文件夹以后就是来存储我们vue项目的一些第三方的配置文件

我们在Plugins目录下创建一个 myAxios.ts的配置文件(封装axios)

myAxios.ts 文件内容如下

import axios from 'axios'

// 创建axios实例。统一配置
const service = axios.create({
  baseURL: "http://xxx.com, // api的base_url
  timeout: 15000 // 请求超时时间
  // .... 其他信息
})

// request拦截器
service.interceptors.request.use(config => {
  //... 获取token,存储token 等操作
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
      return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default service

配置文件写完了还不够,我们需要引入到main.js文件中

import Vue from 'vue'
import App from './App.vue' 
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from '@/plugins/myAxios.ts'
Vue.use(ElementUI);

//替换vue内部的http为axios
Vue.prototype.$http = axios
Vue.config.productionTip = false


new Vue({
  render: h => h(App),
}).$mount('#app')

这句话的意思就是讲vue内置的http的api替换为axios

Vue.prototype.$http = axios

方便我们后续使用axios来请求接口

至此配置就已经全部完成了

使用

this.$http.get("/api/joke/list?num=6")
        .then((res) => {
          console.log(res.data)
        })

这里需要注意下,调用的时候一定要使用 this.$http 不然就会报找不到http这个定义的错误

顺便再分享一个vue上传文件的小案例

<template>
  <div id="app">				
	<el-upload
  class="upload-demo"
  drag
  :on-success="handleFileSuccess"
  :before-upload="beforeFileUpload"
  action="https://jsonplaceholder.typicode.com/posts/"
  multiple>
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<br><br>
<img :src="imageUrl" alt="" class="img"> 
<p>
    <el-input v-model="input" id="input" placeholder=""></el-input>
    <el-button type="primary" plain @click="selectCopy()">复制</el-button>
</p>
    <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->



  </div>
</template>

<script>

export default {
  name: 'App',
  data(){
    return{
      imageUrl:"",
    }
  },
  methods:{

    submitUpload() {
      this.$refs.upload.submit();
    },
     selectCopy() {
    const inputElement = document.querySelector('#input');
    inputElement.select();
    document.execCommand("Copy");

                this.$message({
                    message: '复制成功',
                    type: 'success'
                });
            },

    handleFileSuccess(res,file){
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$message.success("上传图片成功")
      console.log(res)
      // this.input = this.res
      this.input = this.imageUrl
    },
    beforeFileUpload(file){
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size /1024 /1024 < 2;

      if(!isJPG){
        this.$message.error("上传图片只能是JPG格式")
      }
      if(!isLt2M){
        this.$message.error("上传图片大小不能超过 2MB")
      }
      return isJPG && isLt2M;
    }
  }
  
}
</script>

<style  scoped>


#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  
}


</style>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java-superchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值