vue - 组件间通信2

父组件--> 子组件

1. 属性设置

父组件关键代码如下:

<template>
    <Child :child-msg="msg"></Child>
</template>

子组件关键代码如下:

export default {
  name: 'child',
  props: {
    child-msg: String
  }
};

child-msg 为父组件给子组件设置的额外属性值,属性值需在子组件中设置props,子组件中可直接使用child-msg变量。

2. 子组件调用父组件

子组件通过 $parent 获得父组件,通过 $root 获得最上层的组件。

子组件--> 父组件

1. 发送事件/监听事件

子组件中某函数内发送事件:

this.$emit('toparentevent', 'data');

父组件监听事件:

<Child :msg="msg" @toparentevent="todo()"></Child>

toparentevent 为子组件自定义发送事件名称,父组件中@toparentevent为监听事件,todo为父组件处理方法。

2. 父组件直接获取子组件属性或方法

给要调用的子组件起个名字。将名字设置为子组件 ref 属性的值。

<!-- 子组件。 ref的值是组件引用的名称 -->
<child-component ref="aName"></child-component>

父组件中通过 $refs.组件名 来获得子组件,也就可以调用子组件的属性和方法了。

var child = this.$refs.aName
child.属性
child.方法()

父组件通过 $children 可以获得所有直接子组件(父组件的子组件的子组件不是直接子组件)。需要注意 $children 并不保证顺序,也不是响应式的。

Bus中央通信

目前中央通信是解决兄弟间通信,祖父祖孙间通信的最佳方法,不仅限于此,也可以解决父组件子组件间的相互通信。如下图:

扫描二维码关注公众号,回复: 4206371 查看本文章

clipboard.png

各组件可自己定义好组件内接收外部组件的消息事件即可,不用理会是哪个组件发过来;而对于发送事件的组件,亦不用理会这个事件到底怎么发送给我需要发送的组件。

先设置Bus

//bus.js 
import Vue from 'vue'
export default new Vue();

组件内监听事件:

import bus from '@/bus';

export default {
  name: 'childa',
  methods: {
  },
  created() {
    bus.$on('childa-message', function(data) {
      console.log('I get it');
    });
  }
};

发送事件的组件:

import bus from '@/bus';
//方法内执行下面动作
bus.$emit('childa-message', this.data);

猜你喜欢

转载自blog.csdn.net/qq_40954793/article/details/82253121