1.首先是最重要的核心文件--封装Promise -- 文件名:interfaceIndex.js
import axios from 'axios'import qs from 'qs'//请求接口export function request(config) {var host = '/?s='var defer = new Promise(function(resolve, reject) {var requestConfig = {method: config.method,url: host + config.url,data: qs.stringify(config.data)}axios(requestConfig).then(res => {resolve(res.data)})})return defer}
2.编写详细接口文件xxxx.js(注意要引入上一步的文件interfaceIndex.js)
import * as httpServer from './interfaceIndex'export default {//登录loginApi(data) {return httpServer.request({method: 'POST',url: 'App.LoginByUsername', //按照用户名密码登陆data: data})},//按照上面的格式继续添加接口}
3.在xx.vue文件中使用 -- 以登录为例(注意要引入上一步的xxxx.js文件
//前后台交互let obj = {username: username,password: password,token: localStorage.getItem('token')}interfaceFile.loginApi(obj).then(res => {console.log(res)}).catch(err => {//获取数据失败就报错console.log(err)})