vue2.0 父子组件之间的通信问题

概要:

父组件向子组件通信:props属性

子组件向父组件通信:$emit()触发事件,$on()监听事件

在 vue 1.0 中可以使用$dispatch 和 $broadcast来实现 向上派发事件 和 向下广播事件;

事件

说明

$on(事件名)

事件名的类型是字符串(下同),调用它可以通过this.$on()来调用;

$emit(事件名, 参数)

用于触发事件,参数是用于传递给事件的参数。这个用于触发同级事件(当前组件的)

$dispatch(事件名, 参数)

①向上派发事件,用于向父组件传播。

②会首先触发当前组件的同名事件(如果有);

③然后会向上冒泡,当遇到第一个符合的父组件的事件后触发并停止;

④当父组件的事件的返回值设为true会继续冒泡去找下一个。

$broadcast(事件名, 参数)

①向下广播事件,用于向所有子组件传播。

②默认情况是仅限子组件;

③子组件事件的返回值是true,才会继续向该子组件的孙组件派发;

④不会触发自身同名事件;


但是在vue 2.0 已将将该方法迁移了,因为基于组件树结构的事件流方式实在是让人难以理解,并且在组件结构扩展的过程中会变得越来越脆弱。这种事件方式确实不太好,我们也不希望在以后让开发者们太痛苦。并且$dispatch和 $broadcast也没有解决兄弟组件间的通信问题。$dispatch和 $broadcast已经被弃用。请使用更多简明清晰的组件间通信和更好的状态管理方案,如:Vuex.

 

父组件向子组件通信

功能实现:点击click按钮拿到父组件传递过来的属性值,console.log在控制台

建立一个子组件:componentA.vue 内部代码如下:

<template>
	<button @click="onClick">clickMe</button>
</template>
<script>
	export default{
		props:["msgfromfather"],
		methods:{
			onClick:function(){
				console.log(this.msgfromfather)
			}
		}
	}
</script>
App.vue代码如下:

<template>
  <div id="app">
    <component-a msgfromfather="you die!"></component-a>
  </div>
</template>
<script>
import componentA from './components/componenta'
export default {
  name: 'app',
  data:function(){
      return {
        childwords:''
      }
    },
  components: {
    componentA
  },
  methods:{
    listenToMyBoy:function(msg){
      this.childwords = msg
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>



 子组件向父组件通信

功能实现:点击按钮,在上方页面区域打出从子组件传递过来的 msg 参数

componentA.vue 内部代码如下:

<template>
	<button @click="onClick">clickMe</button>
</template>

<script>
	export default{
		data:function(){
			return {
				msg:'hello componenta'
			}
		},
		props:["msgfromfather"],
		methods:{
			onClick:function(){
				console.log(this.msgfromfather)
				this.$emit('child-tell-me-sth',this.msg)
			}
		}
	}
</script>
App.vue代码如下:
<template>
  <div id="app">
  <p>child tell me: {{ childwords }}</p>
    <component-a msgfromfather="you die!"
      @child-tell-me-sth="listenToMyBoy"
    ></component-a>
  </div>
</template>

<script>
import componentA from './components/componenta'

export default {
  name: 'app',
  data:function(){
      return {
        childwords:''
      }
    },
  components: {
    componentA
  },
  methods:{
    listenToMyBoy:function(msg){
      this.childwords = msg
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

在子组件向父组件通信借助了vue2.0中的 $emit() ,子组件在click事件里面:this.$emit('child-tell-me-sth',this.msg),传递了事件名称 "child-tell-me-sth" 和参数 "this.msg" 给父组件,在父组件中打印出来

原文地址:https://www.cnblogs.com/lantinggumo/p/7636710.html