vue中父子组件以及兄弟组件通信

父组件向子组件传值

父组件通过props属性与子组件通信

父组件:

<parent>
    <single-voice  ref="singleVoiceRef" :parent-to-child="singleVoiceData"/>
</parent>

data(){
    return {
        singleVoiceData:'来自父组件的数据'
    }
},
// 父组件调用子组件中的方法,将值传递给子组件
methods:{
this.$refs.singleVoiceRef.openSingleVoice(this.singleVoiceData)
}

子组件通过props来接受数据

props: {
    parentToChild: {
      type: String,
      required: true
    }
  },
  methods:{
   openSingleVoice(SingleVoice) {
	console.log(SingleVoice)
      }
    }

子组件向父组件传值

vue2.0只允许单向数据传递,我们通过出发事件来改变组件的数据

子组件代码:

<template>
    <div @click="open"></div>
</template>

methods: {
   open() {
        this.$emit('showbox','the msg'); //触发showbox方法,'the msg'为向父组件传递的数据
    }
}

父组件代码:

<child @showbox="toshow" :msg="msg"></child> //监听子组件触发的showbox事件,然后调用toshow方法

methods: {
    toshow(msg) {
        this.msg = msg;
    }
}

兄弟组件之间的通信

我们可以实例化一个vue实例,相当于一个第三方

eventVue.$emit(‘function1’,value)

eventVue.$on(‘function1’, (message) => { // 箭头函数接收
})
创建一个公共桥梁 eventVue.js

import Vue from 'vue'
export default new Vue()

兄弟组件内引入 eventVue.js

兄弟组件一

import eventVue from './eventVue.js'
export default {
  methods: {
  fetchPhoneListToWindow(val) {
      this.voiceChatData = val
      eventVue.$emit('phoneListInfo', this.voiceChatData) // $emit这个方法会触发一个事件
      // this.handleUpdateChatList(this.voiceChatData)
    }
  }
}

兄弟组件二

import eventVue from './eventVue.js'
export default {
  methods: {
phoneListToWindow() {
      eventVue.$on('phoneListInfo', (message) => { // 与phoneBook组件通信
        console.log(message)
      })
    }
    }

注意:兄弟组件之间的通信,要确保当前兄弟组件已经被加载,否则会调用失败

猜你喜欢

转载自blog.csdn.net/weixin_43254676/article/details/87976698