假如我们页面中有许多个组件组成,每个组件都有自己的json数据,如果每个组件都单独请求一个ajax,那么整个页面就会发送许多个ajax请求,这样的页面运行肯定是很慢的
那么怎么样做才合理呢?
我们希望整个首页只请求一个json数据,也就是只发送一个ajax请求
对于类似上面这样情况,我们把ajax请求放在Home.vue中,然后通过子父组件传值,把每个子组件需要的数据都传给子组件
使用方法:
<template>
<div>
<home-header :city="city"></home-header>
<home-swiper :list="swiperList"></home-swiper>
<home-icons :list="iconList"></home-icons>
<home-recommend :list="recommendList"></home-recommend>
<home-weekend :list="weekendList"></home-weekend>
</div>
</template>
<script>
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'
export default {
name: 'Home',
components: {
HomeHeader,
HomeSwiper,
HomeIcons,
HomeRecommend,
HomeWeekend
},
data () {
return {
city: '',
swiperList: [],
iconList: [],
recommendList: [],
weekendList: []
}
},
methods: {
getHomeInfo: function () {
axios.get('/api/index.json').then(this.getHomeInfoSucc)
},
getHomeInfoSucc: function (res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
this.city = data.city
this.swiperList = data.swiperList
this.iconList = data.iconList
this.recommendList = data.recommendList
this.weekendList = data.weekendList
}
}
},
mounted () {
this.getHomeInfo()
}
}
</script>
<style>
</style>
我们把静态的json数据放在static里面mock文件夹里面,但是我们不想让他上线:
这样就不会提交到本地仓库和线上仓库
但是我们现在用的都是本地模拟的接口地址,假如我们的代码要上线,肯定不能填成本地地址,所以要写成api这种格式
所以我们就需要一种能够将我们的api转发到本地的mock文件夹下的功能,webpack-dev-server就为我们提供了这样的功能