在vue项目中使用axios方法封装全局调用

223 阅读1分钟

要想对后端提供的接口全局使用,就要进行全局封装, 首先可以在utils文件夹下面新建一个js文件,来写所需的方法体

image.png

然后将接口引入进行调用

`import { departmentTree } from "../api/user" import request from '@/utils/request' // import axios from "axios" function departmentTree1() { let options1 = null departmentTree().then((res) => { options1 = res }) }

export default { departmentTree1 }`

image.png

将方法体return出来,并且在全局main.js中申明

image.png

这样就可以在局部页面中调用

image.png


如果是需要返回方法体返回来的数据可以使用Promise(resolve, reject)返回方法体返回来的参数,并使用

`import { departmentTree } from "../api/user" import request from '@/utils/request' // import axios from "axios" function departmentTree1() { return new Promise(async (resolve, reject) => { let options1 = null await departmentTree().then((res) => { options1 = res })

resolve(options1)

})

}

export default { departmentTree1 }`

这样全局封装同上,局部调用直接进行赋值

async created() { // 重要:部门单位列表处理结果 this.SubList = await this.$utils.departmentTree1();