在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>
Comments NOTHING