这个问题是我在用nuxt写前端的时候遇到的
1.首先是父组件获取数据并传递给子组件
<template>
<div class="">
<detail :detailData="detailData"/>
</div>
</template>
<script>
import detail from "@/components/detail";
import {getScenicSpotDetail} from "@/api";
export default {
name: "scenic_detail",
components: {
detail
},
data() {
return {
detailData: {}
}
},
created() {
this.getDetail()
},
methods: {
async getDetail() {
let res = await getScenicSpotDetail(this.$route.params.id)
this.detailData = res.data
}
}
}
</script>
<style scoped>
</style>
2.子组件接收数据并传递给孙子组件
<section class="info-container w-full h-auto">
<div class="float-left mx-48" style="width: 640px; height: 400px">
<detail-swiper :photosList="detailData.photosList"/>
</div>
<div class="float-left text-3xl px-8 pt-6 bg-black bg-opacity-60 text-white" style="width: 900px; height: 400px"> {{ detailData.description}}</div>
</section>
export default {
name: "detail",
props: ['detailData'],
components: {
detailSwiper,
pagination
}
}
3.孙子组件接收数据
<template>
<!-- 我的轮播图组件,第一张和最后一张都是一样的-->
<div class="w-full h-full overflow-x-hidden">
<div class="image-container h-full">
<img v-for="img in imageList" :src="img" alt="" class="w-1/5 h-full object-cover float-left">
</div>
</div>
</template>
<script>
import {getRandomList ,fillList} from "@/utils/arrayUtil";
export default {
name: "detailSwiper",
props: ['photosList'],
computed: {
imageList() {
if (this.photosList === undefined) {
return []
}
let list = []
for (const photo of this.photosList) {
list.push(photo.picture)
}
let newList = []
// 多于4张照片就随机取4张
if (list.length > 4) {
newList = getRandomList(list, 4)
} else if (list.length < 4) { //少于4张照片就补齐4张
newList = fillList(list, 4)
} else {
newList = list
}
newList.push(newList[0])
return newList
}
},
methods: {
}
}
</script>
<style scoped>
.image-container{
width: calc(100% * 5);
animation: swiper 10s infinite;
}
@keyframes swiper {
0%{transform: translateX(0)}
10%{transform: translateX(0)}
25%{transform: translateX(-20%)}
35%{transform: translateX(-20%)}
50%{transform: translateX(-40%)}
60%{transform: translateX(-40%)}
75%{transform: translateX(-60%)}
85%{transform: translateX(-60%)}
100%{transform: translateX(-80%)}
}
</style>
由于我是用计算属性来处理传递过来的数据的,所以就顺带着在计算属性里判断传递过来的数据是否有定义,没定义的话就直接返回空数组,等下一次真正的数据传递过来的时候计算属性又会重新计算了。这姑且算是目前我的一个笨拙的解决办法吧。
Q.E.D.