首先先展示下json的数据
city,swiperList部分
iconList部分
recommendList部分
weekendList部分
好了 现在将各个组件的数据全部替换成获取到的json数据
1.首先在Home.vue中分发数据到各个子组件中:
<template>
<div>
//3.将各个变量传递给各个子组件
<home-header :city="city"></home-header>
<home-swiper :list="swiperList"></home-swiper>
<home-icons :list="iconList"></home-icons>
<home-recommend :list="recommend"></home-recommend>
<home-weekend :list="weekendList"></home-weekend>
<div>test</div>
</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 () {
//1.先定义各个组件传递数据的变量
return {
city: '',
swiperList: [],
iconList: [],
recommend: [],
weekendList: []
}
},
methods: {
getHomeInfo () {
axios.get('/api/index.json')
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) {
//2.然后将index.json的数据进行分发
res = res.data
//如果res.ret的值为true,并且data有数据
if (res.ret && res.data) {
const data = res.data
this.city = data.city
this.swiperList = data.swiperList
this.iconList = data.iconList
this.recommend = data.recommendList
this.weekendList = data.weekendList
}
}
},
mounted () {
this.getHomeInfo()
}
}
</script>
<style>
</style>
接下来就是各个子组件的接收:
// header.vue
<script>
export default {
name: 'HomeHeader',
props: {
city: String
}
}
</script>
<div class="Header-right">
{{this.city}}
<span class="iconfont arrow-icon"></span>
</div>
//swiper.vue
<script>
export default {
name: 'HomeSwiper',
props: {
list: Array
},
data () {
return {
swiperOption: {
pagination: '.swiper-pagination',
loop: true
}
}
},
//这个计算函数时为了让滚动图从第一页开始滚动。
computed: {
showSwiper () {
return this.list.length
}
}
}
</script>
<swiper :options="swiperOption" v-if="showSwiper">
<swiper-slide v-for="item of list" :key="item.id">
<img class="swiper-img" :src="item.imgUrl" />
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
<div class="swiper-button-next" slot="button-next"></div> -->
</swiper>
//recommend.vue
<script>
export default {
name: 'HomeRecommend',
props: {
list: Array
}
}
</script>
<li
class="item border-bottom"
v-for="item of list"
:key="item.id"
>
//icons.vue
<script>
export default {
name: 'HomeIcons',
props: {
list: Array
},
//这里是设置图标不要自己滚动来滚动去
data () {
return {
swiperOption: {
autoplay: false
}
}
},
computed: {
pages () {
const pages = []
this.list.forEach((item, index) => {
const page = Math.floor(index / 8)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
}
}
</script>
//weekend.vue
<script>
export default {
name: 'HomeWeekend',
props: {
list: Array
}
}
</script>
<li
class="item border-bottom"
v-for="item of list"
:key="item.id"
>