通過v-on
監聽 和$emit
觸發來實現:
1、在父組件
中 通過v-on
監聽 當前實例上的 自定義事件。
2、在子組件
中 通過'$emit'
觸發 當前實例上的 自定義事件。
示例:
父組件:
<template> <div class="fatherPageWrap"> <h1>這是父組件</h1> <!-- 引入子組件,v-on監聽自定義事件 --> <emitChild v-on:emitMethods="fatherMethod"></emitChild> </div> </template> <script type="text/javascript"> import emitChild from '@/page/children/emitChild.vue'; export default{ data () { return {} }, components : { emitChild }, methods : { fatherMethod(params){ alert(JSON.stringify(params)); } } } </script>
子組件:
<template> <div class="childPageWrap"> <h1>這是子組件</h1> </div> </template> <script type="text/javascript"> export default{ data () { return {} }, mounted () { //通過 emit 觸發 this.$emit('emitMethods',{"name" : 123}); } } </script>
結果:
子組件 會調用 父組件的fatherMethod
方法,該並且會alert
傳遞過去的參數:{"name":123}