递归组件如何显示bus传递过来的值,自己调用自己的时候,请老师在仔细看看
# 具体遇到的问题
# 报错信息的截图
# 相关课程内容截图
# 尝试过的解决思路和结果
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
<template>
<div>
<detail-banner :bannerImg="bannerImg" :sightName="sightName" :gallaryImgs="gallaryImgs"></detail-banner>
<detail-header></detail-header>
<div class="content">
<!-- <detail-list :categoryList="categoryList"></detail-list> -->
<detail-list></detail-list>
</div>
</div>
</template>
<script>
import DetailBanner from './components/Banner'
import DetailHeader from './components/Header'
import DetailList from './components/List'
import axios from 'axios'
import bus from '../../bus'
export default {
name: 'detail', // name 的用处一: 递归组件 用处二: 对某个页面取消缓存的时候 exclude="detail"
data () {
return {
bannerImg: '',
sightName: '',
gallaryImgs: []
// categoryList: []
}
},
components: {
DetailBanner,
DetailHeader,
DetailList
},
methods: {
getDetailInfo () {
axios.get('/api/detail.json', {
params: {
id: this.$route.params.id
}
}).then(this.getDetailInfoSucc)
},
getDetailInfoSucc (res) {
const data = res.data
if (data.ret && data.data) {
const res = data.data
this.bannerImg = res.bannerImg
this.sightName = res.sightName
this.gallaryImgs = res.gallaryImgs
// this.categoryList = res.categoryList
bus.$emit('categoryListData', res.categoryList)
}
}
},
mounted () {
this.getDetailInfo()
}
}
</script>
<style lang="stylus" scoped>
.content
height 50rem
</style>
----------------------------------
<template>
<div class="detail-list">
<div class="item" v-for="(item, index) in categoryList" :key="index">
<div class="item-title border-bottom">
<span class="item-title-icon"></span>
{{item.title}}
</div>
<div class="item-children" v-if="item.children">
<!-- 递归组件 自己调用自己 -->
<!-- <detail-list :categoryList="item.children"></detail-list> -->
<detail-list></detail-list>
</div>
</div>
</div>
</template>
<script>
import bus from '../../../bus'
export default {
name: 'detailList',
// props: {
// categoryList: {
// type: Array
// }
// },
data () {
return {
categoryList: []
}
},
mounted () {
bus.$on('categoryListData', (val) => {
this.categoryList = val
})
}
}
</script>
<style lang="stylus" scoped>
.detail-list
.item
.item-title
line-height .8rem
font-size .32rem
padding 0 .2rem
.item-title-icon
position relative
top .06rem
left .06rem
display inline-block
width .36rem
height .36rem
margin-right .1rem
background url(http://s.qunarzz.com/piao/image/touch/sight/detail.png) 0 -.45rem no-repeat
background-size .4rem 3rem
.item-children
padding 0 .2rem
</style>
正在回答
同学你好,老师仔细研究了一下发现使用bus没法实现递归组件传值。bus在传递数据时,需要利用事件的形式,即$emit触发事件,$on监听事件。在detail-list内,可以在mounted事件中,使用$on监听detail组件传过来的数据,但是detail-list内,没法既$emit触发事件又$on监听自己的事件,这两个事件的触发时机,很难控制,所以建议同学掌握视频中老师的写法即可。
祝学习愉快!
- 参与学习 人
- 提交作业 239 份
- 解答问题 10739 个
本阶段带你深入前端开发的肌理,通过ES6基础知识和前端主流高级框架的学习,助你快速构建企业级移动webAPP应用,进入职场的终极battle
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星