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

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 12:46   30   0

父组件向子组件传值

父组件通过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: {
 // 点击通讯录与员工进行语音聊天
    handleChatStaff(staffInfo) {
      console.log(staffInfo)
      this.staffInfo = staffInfo
      eventVue.$emit('updateChatList', this.staffInfo)
    },
  }
}

兄弟组件二

import eventVue from './eventVue.js'
export default {
 created() {
    this.updateList()
  },
  methods: {
    updateList() {
      eventVue.$on('updateChatList', (message) => { // 与phoneBook组件通信
        console.log(message)
        this.updateChatListEvent()
      })
    },
    // 更新聊天列表
    updateChatListEvent() {},
    }

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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP