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錯誤

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM