Vuejs 2.0 子組件訪問/調用父組件的方法(範例程式碼),vuejs範例程式碼

來源:互聯網
上載者:User

Vuejs 2.0 子組件訪問/調用父組件的方法(範例程式碼),vuejs範例程式碼

有時候因為布局問題,需要子組件 把資料 傳給父組件,並執行父級的某個方法,不多說上代碼:

子組件:

<template>   <div class="isShowing" ref="isShowing">     <div class="menu-wrapper" ref="scroll_warpper" v-show="!hid_show_switch">       <ul ref="scroll_warpper_ul">         <li class="menu-item" @click="goToFatherDetail(233)">         </li>       </ul>     </div>     <v-loading class="isloading" v-show="hid_show_switch"></v-loading>   </div> </template> <script type="text/ecmascript-6">   export default {     methods: {       goToFatherDetail (itemId) {         // this.$parent.$router.push('goToDetail');         console.log('子組件方法走了' + itemId);         this.$emit('refreshbizlines', itemId); /* <span style="font-family: Arial, Helvetica, sans-serif;">itemId就是子要傳的資料 - 這裡很重要,refreshbizlines就是父組件$on監測的自訂函數不是父組件的自訂函數。*/</span>       }     }   }; </script> 

父組件:

<template>   <div class="main-wrapper">       <div class="tab-wrapper">         <div class="tab-item">           <router-link to="/isShowing" class="table-item-text">正在熱映</router-link>         </div>         <div class="tab-item">           <router-link to="/willShow" class="table-item-text">即將上映</router-link>         </div>       </div>     </div>     <router-view class="items-show" v-on:refreshbizlines="goToDetail" keep-alive></router-view>   </div> </template> <script type="text/ecmascript-6">   export default {     methods: {       goToDetail (itemId) {         console.log('父組件走你:' + itemId);       }     }<strong>   }; </script></strong> 

父組件用 v-on 來做個監測的函數來檢測,最終產生的程式碼是 類似

on: {   "refreshbizlines": function($event) {    _vm.goToDetail(123)}}

所以原理就是 子組件 訪問 父組件的 檢測函數 refreshbizlines ,訪問了,則執行 refreshbizline 下面的 函數

goToDetail -- 也就是父組件的

goToDetail函數

注意 父組件 的

v-on:refreshbizlines="goToDetail"

 一定要放在 你父組件調用子組件的 模組名上。

總結

以上所述是小編給大家介紹的Vuejs 2.0 子組件訪問/調用父組件的方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.