vue跨组件传值
一、背景介绍
需要用vue做点击查看图片,弹出图片的功能。点击【查看图片】按钮在最外层(父层),中间还有一层div和一层table,图片的组件在最里层(子层)。
层级关系如下:
div.content->div.ivu-table-wrapper->div.content->div.ivu-layout-content->showPhoto(最终方法)
二、页面名称
1、salesDetails.vue:父组件页面(最外层)
iview轮播图组件:
<Carousel v-model="value1" class="photo" v-if="admissionShow"> <Button class="close" icon="md-close" label="large" @click="admissionShow = false"></Button> <CarouselItem> <img v-for="item in carouselItem" :key="item" :src="{item}"> </CarouselItem> </Carousel>
data:
data() { return { value1: 0, admissionShow: false, }; },
methods:
showPhoto(url) { this.carouselItem = [url]; this.admissionShow = true; },
2、ticketInfoTable.vue组件(中间的组件页面)
什么都不需要写
3、table-expand.vue组件(最里层组件)
iview:
<Col span="5"> <span class="expand-key">入园照片:</span> <span class="expand-value"><Button size="small" @click="admissionPhoto(row.touristimg_url)">查看照片</Button></span> </Col>
methods:
methods: { admissionPhoto(url) { console.log(this); this.$parent.$parent.$parent.$parent.showPhoto(url); }, },
三、总结
直接用
this.$parent.$parent.$parent.$parent.showPhoto(url);
来获取跨组件的值,此代码意思是把【url】传递到salesDetails.vue的showPhoto方法里。
需要注意的是要写几个parent才可以,方法:在this获取的对象中,点几下$parent找到目标方法就写几个$parent,如果$parent个数写不对,会报【方法名x()不是一个函数】的js错误