有時候因為布局問題,需要子組件 把資料 傳給父組件,並執行父級的某個方法,本文主要介紹了Vuejs 2.0 子組件訪問/調用父組件的方法(範例程式碼),需要的朋友可以參考下,希望能協助到大家。
不多說上代碼:
子組件:
<template> <p class="isShowing" ref="isShowing"> <p 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> </p> <v-loading class="isloading" v-show="hid_show_switch"></v-loading> </p> </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> <p class="main-wrapper"> <p class="tab-wrapper"> <p class="tab-item"> <router-link to="/isShowing" class="table-item-text">正在熱映</router-link> </p> <p class="tab-item"> <router-link to="/willShow" class="table-item-text">即將上映</router-link> </p> </p> </p> <router-view class="items-show" v-on:refreshbizlines="goToDetail" keep-alive></router-view> </p> </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"
一定要放在 你父組件調用子組件的 模組名上。