作者:文竹 | 来源:互联网 | 2022-03-10 00:51
这篇文章主要给大家介绍了关于Vue项目中如何封装axios(统一管理http请求)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1、需求说明
在使用Vue.js框架开发前端项目时,会经常发送ajax请求服务端接口,在开发过程中,需要对axios进一步封装,方便在项目中的使用。
2、Vue项目结构
在本地创建Vue项目,目录结构如下:
- public 静态资源文件
- src
|- assets 静态资源目录
|- components 公共组件目录
|- http axios封装目录
|- router 路由管理目录
|- store 状态管理目录
|- views 视图组件目录
|- App.vue 根组件
|- main.js 入口文件
- package.json npm配置文件
在Vue项目中创建 http目录 作为axios的管理目录,在 http目录 下两个文件,分别是
- /http/index.js 封装axios方法的文件
- /http/api.js 统一管理接口的文件
3、代码示例
/http/api.js文件代码如下:
1 2 3 4 5 6 | export default {
'users_add' : '/users/add' ,
'users_find' : '/users/find' ,
'users_update' : '/users/update' ,
'users_delete' : '/users/delete'
}
|
/http/index.js文件代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import axios from 'axios'
import api from './api'
let instance = axios.create({
timeout: 5000
})
instance.interceptors.request.use(cOnfig=>{
console.log( '正在请求……' )
return config
},err=>{
console.error( '请求失败' ,err)
})
instance.interceptors.response.use(res=>{
console.log( '请求成功!' )
return res
},err=>{
console.log( '响应失败!' ,err)
})
async function http(option = {}) {
let result = null
if (option.method === 'get' || option.method === 'delete' ){
await instance[option.method](
api[option.url],
{params: option.params}
).then(res=>{
result = res.data
}). catch (err=>{
result = err
})
} else if (option.method === 'post' || option.method === 'put' ){
await instance[option.method](
api[option.url],
option.params
).then(res=>{
result = res.data
}). catch (err=>{
result = err
})
}
return result
}
export default http
|
在main.js入口文件中引入封装好的 /http/index.js 文件,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from './http'
Vue.config.productiOnTip= false
Vue.prototype.$http = http
Vue.use(Elementui)
new Vue({
router,
store,
render: h => h(App)
}).$mount( '#app' )
|
在App.vue根组件中测试axios请求,示例代码如下:
1 2 3 4 5 | <template>
<div>
<button @click= "getDate" >发送请求
</button></div>
</template>
|
这里需要有 http://localhost:3000/users/find 接口,不然请求会失败!
4、效果演示
启动Vue项目,在浏览器中访问Vue项目的地址,我的地址是 http://localhost:8080,点击按钮发送请求,获取的结果如下图所示。
到此,在Vue项目中就完成了简单的axios封装,你也可以根据自己的实际需求对axios进行封装,本文只是提供参考。
到此这篇关于Vue项目中如何封装axios(统一管理http请求)的文章就介绍到这了,更多相关Vue封装axios管理http请求内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!