Vue js封装接口

天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/

1.安装axios

复制代码
npm install axios -g

2.在src下新建一个Api文件夹,再创建一个js文件

复制代码
import axios from 'axios'
let configuration = {
	url:"http://localhost:9090"
}
/**
 * 请求项目数据的请求体
 */
async function http({ url, method, param }) {
	const httpUrl = configuration.url + url
	if (method === 'GET') {
		httpUrl + jsonToGetParams(param)
	}
	const { data } = await axios({
		url: httpUrl,
		method: method ? method : 'GET',
		data: method === 'GET' ? {} : param,
		headers: {
			'content-type': 'application/json',
			token: localStorage.getItem('token') || ''
		}
	})
	return data
}
async function ask(e) {
	return http({
		url: e[0],
		method: e[1],
		param: e[2]
	})
}
export { ask }

/**
 * GET参数转字符串
 * @param jsonObj
 * @returns {string}
 */
function jsonToGetParams(jsonObj) {
	const params = Object.entries(jsonObj)
		.map(([key, value]) => `${key}=${value}`)
		.join('&')
	if (params.length >= 1) {
		return '?' + params
	} else {
		return params
	}
}

3.在src下新建一个Interface文件夹,里面单独存放接口,用户接口就创建UserApi.js文件,文件接口就创建FileApi.js

复制代码
import {ask} from "../Api/requestBody";

/**
 * 查询用户接口
 */
export function getQueryUser(param){
    return ask(['/user/queryUser','GET',param]);
}

4.来到vue页面调用

复制代码
 getQueryUserFun(){
      getQueryUser({
        id:"2222"
      }).then(res=>{
        console.log(res)
      })
    }
相关推荐
光影少年2 小时前
angular生态及学习路线
前端·学习·angular.js
記億揺晃着的那天4 小时前
Vue + Element UI 表格自适应高度如何做?
javascript·vue.js·ui
无尽夏_4 小时前
HTML5(前端基础)
前端·html·html5
Jagger_4 小时前
敏捷开发流程-精简版
前端·后端
FIN66684 小时前
昂瑞微冲刺科创板:创新驱动,引领射频芯片国产化新征程
前端·安全·前端框架·信息与通信·芯片
GISer_Jing4 小时前
ByteDance——jy真题
前端·javascript·面试
睡美人的小仙女1274 小时前
浏览器为何屏蔽本地文件路径?
前端
真的想不出名儿4 小时前
Vue 中 props 传递数据的坑
前端·javascript·vue.js
FIN66684 小时前
昂瑞微:深耕射频“芯”赛道以硬核实力冲刺科创板大门
前端·人工智能·科技·前端框架·信息与通信·智能
阳光阴郁大boy4 小时前
星座运势网站技术解析:从零打造现代化Web应用
前端·javascript