父组件Home传值给子组件Header
在Home组件中写入
data () {
return {
city: ''
}
},
并绑定:city="city"
<template>
<div>
<home-header :city="city"></home-header>
<home-swiper></home-swiper>
<home-icons></home-icons>
<home-recommend></home-recommend>
<home-weekend></home-weekend>
</div>
</template>
然后在子组件Header中写入props对象来接收这个数据,并指定这个数据只能是字符串类型
<script>
export default {
name: 'HomeHeader',
props: {
city: String
}
}
</script>
在子组件Header中使用city数据
<div class="header-right">
{{this.city}}
<span class="iconfont arrow-icon"></span>
</div>
上节我们已经获取了模拟数据,现在就需要使用了
在Home组件中改变代码
<template>
<div>
<home-header :city="city"></home-header>
<home-swiper></home-swiper>
<home-icons></home-icons>
<home-recommend></home-recommend>
<home-weekend></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: ''
}
},
methods: {
getHomeInfo () {
axios.get('/api/index.json')
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
this.city = data.city
}
}
},
mounted () {
this.getHomeInfo()
}
}
</script>
<style scoped>
</style>
其他的父子组件间的传值同上,但这里有一点,在轮播图Swiper这个组件中,轮播的第一张图却是整个循环列表中的最后一张,这是因为swiper初始化创建是根据空数组创建的,只要让swiper创建的时候是一个最终数组而不是一个空数组就可以了,所以在Swiper标签上加v-if=‘swiperList.length’就可以了
<template>
<div class="wrapper">
<swiper :options="swiperOption" v-if="swiperList.length">
<swiper-slide v-for="item of swiperList" :key="item.id">
<img :src="item.imgUrl" alt="图片" class="swiper-img">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</div>
</template>
但是,在模板里尽量不要出现逻辑性的代码,所以我们把它放在计算属性里
<template>
<div class="wrapper">
<swiper :options="swiperOption" v-if="showSwiper">
<swiper-slide v-for="item of swiperList" :key="item.id">
<img :src="item.imgUrl" alt="图片" class="swiper-img">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</div>
</template>
<script>
export default {
name: 'HomeSwiper',
props: {
swiperList: Array
},
data: function () {
return {
swiperOption: {
pagination: '.swiper-pagination',
loop: true
}
}
},
computed: {
showSwiper: function () {
return this.swiperList.length
}
}
}
</script>