一、在src目录下配置两个文件夹api和config
二、api负责mock数据的管理和ajax请求的二次封装
api/index.js
import request from "./request";
export default {
getData () {
return request({
url: '/home/getData',
method: 'get',
mock: true
})
},
getCityData () {
return request({
url: '/city/getCityData',
method: 'get',
mock: true
})
},
getDetailData (params) {
return request({
url: '/detail/getDetailData',
method: 'get',
mock: true,
data: params
})
},
}
api/request.js
import axios from 'axios'
import config from '../config'
import { Message } from 'element-ui';
const NETWORK_ERROR = '网络请求异常,请稍后重试...'
// 创建一个axios实例对象
const service = axios.create({
baseURL: config.baseApi
})
// 请求拦截器
service.interceptors.request.use((req) => {
return req
})
// 响应拦截器
service.interceptors.response.use((res) => {
const { code, data, msg } = res.data
// 根据后端协商而定
if (code == 200) {
return data
} else {
// 网络请求错误
console.log(msg || NETWORK_ERROR);
Message.error('网络异常,请稍后重试...')
return Promise.reject(msg || NETWORK_ERROR)
}
})
// 封装的核心函数
function request (options) {
options.method = options.method || 'get'
// toLowerCase()转换成小写
if (options.method.toLowerCase() == 'get') {
options.params = options.data
}
// 对mock的处理,拿到mock总开关
let isMock = config.mock
// 总开关为true,单独设置我们想要的接口为false
if (typeof options.mock !== 'undefined' ) {
isMock = options.mock
}
// 对线上环境处理
if (config.env == 'prod') {
// 不给用到mock接口的机会
service.defaults.baseURL = config.baseApi
} else {
service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
}
return service(options)
}
export default request
三、config是对三种环境的配置,配置baseApi和mockApi
config/index.js
const env = process.env.NODE_ENV || 'prod'
const EnvConfig = {
development: {
baseApi: '/api',
mockApi: 'https://www.fastmock.site/mock/a930ca4e9d1d4e1a33eba0e7f7489f83/api'
},
test: {
baseApi: '//test.future.com/api',
mockApi: 'https://www.fastmock.site/mock/a930ca4e9d1d4e1a33eba0e7f7489f83/api'
},
prod: {
baseApi: '//future.com/api',
mockApi: 'https://www.fastmock.site/mock/a930ca4e9d1d4e1a33eba0e7f7489f83/api'
}
}
export default {
env,
// mock的总开关
mock: true,
...EnvConfig[env]
}
四、 在main.js中,全局挂载api
import api from './api'
Vue.prototype.$api = api
安装axios
cnpm i axios -S
五、发送ajax请求
export default {
data () {
return {
swiperList: []
}
},
methods: {
async getHomeInfo () {
let res = await this.$api.getData()
this.swiperList = res.swiperList
}
},
mounted () {
this.getHomeInfo()
}
}