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實現組件之間的聯動,絕對有你想了解的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM