封装Axios对象
- 在
src
目录下创建 utils
目录及 utils
下面创建 request.js
文件
- 进行封装
import axios from 'axios'
//1. 创建axios对象
const service = axios.create()
//2. 请求拦截器
service.interceptors.request.use(
config => {
return config
},
error => {
Promise.reject(error)
}
)
//3. 响应拦截器
service.interceptors.response.use(
response => {
//判断code码
return response.data
},
error => {
return Promise.reject(error)
}
)
export default service
- 测试 新建
src/test.js
和新建测试数据
[
{ "id": 1, "name": "张三 1" },
{ "id": 2, "name": "张三 2" },
{ "id": 3, "name": "张三 3" },
{ "id": 4, "name": "张三 4" }
]
import request from '../utils/request'
export default {
getList() {
const req = request({
method: 'get',
url: '/db.json',
})
return req
},
}
<template>
<div>
<div v-for="(item, index) in list" :key="index">{{ item.id }} == {{ item.name }}</div>
</div>
</template>
<script>
import testApi from '../api/test'
import _ from 'lodash'
export default {
data() {
return {
list: [],
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
testApi.getList().then(response => {
console.log(response)
this.list = response
})
},
},
props: {
msg: String,
},
}
</script>
<style scoped></style>