Vue 父組件調用子組件方法


Vue 父組件調用子組件方法

在很多時候,我們需要使用到父子組件,例如嵌套彈窗,這時候可以使用父子組件通信,或者父子組件方法調用,在這里使用到了父組件調用子組件的方法來實現功能。

通過 ref 調用子組件方法

這種方法是比較簡便的,其他方法可另外學習。

父組件代碼

<!-- 父組件 -->
<template>
  <div>  
      <div class="more-action">
          <el-popover placement="bottom" width="100" trigger="click">
              <!-- 舉報按鈕 -->
              <div class="report" @click="openchildReport(orderData.id)">舉報</div>

              <i slot="reference" class="el-icon-more"></i>
          </el-popover>
      </div>
     <!-- 調用子組件,通過ref關聯子組件 -->
     <mainOrderReport ref="child"></mainOrderReport>
  </div>
</template>

<script>
    import mainOrderReport from "@/views/mainOrderReport/index"
    export default {
        //子組件注冊
        components: {
            mainOrderReport
        },
        methods: {
            //點擊舉報按鈕觸發事件
            openchildReport(data) {
                //調用子組件方法,並傳參過去
                this.$refs.child.openReport(data);
            },
        }
    }
</script>

通過ref 關聯子組件,調用子組件方法並傳遞參數。

子組件代碼

<template>
  <div>
    <el-dialog title="選擇舉報類型" :visible.sync="reportValue" :close-on-click-modal="false" :append-to-body="true">
    </el-dialog> 
  </div>
</template>

<script>
export default {
    data() {
      return {
        form: {},
        reportValue: false,
      }
    },
    //被父組件調用,並接收參數
    openReport(data) {
        console.log("mainID:" + data);
        this.reportValue = true
        this.form.mainID = data
    },
}
</script>

子組件方法被調用,並獲取到參數。

該方法是比較簡便,推薦大家使用。至於另外的父子組件通信,不滿足需求的情況下可另行學習。


免責聲明!

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



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