Vue--子组件之间相互调用及传值
父组件
创建子组件公用的空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>
借鉴博客
版权声明:本文为lvxhs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。