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>

借鉴博客

vue 事件派发和监听 (两种方法)
vue2中$emit $on $off实现组件之间的联动,绝对有你想了解的

posted @ 2020-11-02 17:00  吕少少  阅读(1808)  评论(0编辑  收藏  举报