父組件
創建子組件公用的空vue
變量,為pubVue
,並傳給需要互相傳參/互相調用方法的兩個子組件
<template> <div> <btn-tools :pubVue="pubVue" /> <table-list :pubVue="pubVue" /> </div> </template> <script> // 組件引用 import TableList from './components/table-list' import BtnTools from './components/btn-tools' import Vue from 'vue' export default { name: 'PDmaterialList', components: { TableList, BtnTools }, data() { return { pubVue: new Vue() } } } </script>
子組件一 $emit發送事件
<template> <div> <el-button icon="el-icon-search" type="primary" @click="test" /> </div> </template> <script> export default { props: { pubVue: { type: Object } }, methods: { test() { console.log('方法派發') this.pubVue.$emit('YOUR_EVENT_NAME', { name: '張三' }) } } } </script>
子組件二 $on監聽事件
<template> <div> <div>子組件二</div> </div> </template> <script> export default { props: { pubVue: { type: Object } }, mounted() { this.pubVue.$on('YOUR_EVENT_NAME', data => { console.log('方法監聽', data) }) } } </script>