父元件
建立子元件公用的空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>