我封的方法
import axios from "axios";
export default function ajax( url = '', params = { }, type = 'GET' ){
//1.定义promise对象
let promise;
return new Promise( (resolve, reject) =>{
//2.判断请求方式
if('GET' === type){
//2.1.拼接请求字符串
let paramsStr = '';
Object.keys(params).forEach(key =>{
paramsStr += key + '=' + params[key] + '&'
})
//2.2.过滤最后的&
if(paramsStr !== ''){
paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
}
//2.3.完整路径
url += '?' + paramsStr
//2.4.发送GET请求
promise = axios.get(url)
}else if('POST' === type){
promise = axios.post(url, params)
}
//3.返回请求的结果
promise
.then( (response) =>{
resolve(response.data)
})
.catch( error =>{
reject(error)
})
})
}
我写的请求
import ajax from './ajax'
//1. 基础路径
const BASE_URL = 'http://10.213.32.101/:9999';
//2. 请求方法
//2.1 请求首页轮播图
export const getHomeSwiper = ()=>ajax( BASE_URL + '/advertising/info/banners' )
HTML页面中的结构
<div class="block" v-if="homeSwiper.length > 0">
<el-carousel trigger="click" height="600px" ref="carousel" @click.native="linkTo">
<el-carousel-item v-for="(swiper, index) in homeSwiper" :key="index" >
<img :src="swiper.imageUrl" class="image">
</el-carousel-item>
</el-carousel>
</div>
页面请求
computed:{
...mapState(['homeSwiper'])
},
mounted(){
//1. 请求轮播图数据
this.$store.dispatch('reqHomeSwiper')
}