详解vue中的组件通信的几种方式

1.父组件向子组件传值(绑定属性):

首先我们定义一个父组件father.vue:

<template>
	<div>
		<h1>父组件</h1>
		<p>{{mydata}}</p>
		<hr/>
		<!--向子组件传值:绑定属性tosondata,father为传入的值-->
		<son :tosondata="father" @getdata="getsondata"></son>
		<!--接收子组件的传值:通过子组件触发getdata事件,父组件在getsondata事件中接收-->
		<hr/>
		<brother></brother>
	</div>
</template>

<script>
	import son from './son.vue'
	import brother from './brother.vue'
	export default{
		data(){
			return{
			father:"我是父组件的数据,已经接收到了",
			mydata:''
			}
		},
		components:{
			son,
			brother
		},
		methods:{
			getsondata(value){
//				接收子组件传入的值value
				this.mydata=value
			}
		}
	}
</script>

子组件son.vue:

<template>
	<div>
		<h1>子组件</h1>
		<p>{{tosondata}}</p>
		<h2>{{mydata1}}</h2>
		<button @click="btn">摁我传值父组件</button>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				sonmsg:'我是子组件的数据',
				mydata1:''
			}
		},
	    props:{
	    	tosondata:String
	    },
		methods:{
			btn(){
//				触发getdata事件,传入sonmsg值
				this.$emit('getdata',this.sonmsg)
			}
		},
		created(){
// 监听兄弟组件的自定义事件,并接受传入的值
			this.$eventhande.$on('change',(val)=>{
				this.mydata1=val
			})
		}
	}
</script>

2.子组件向父组件传值($emit触发自定义事件),如上图

3.兄弟组件传值(定义一个vue空实例作为桥梁):

首先我们在main.js中定义vue空实例

//创建vue空实例
let hub=new Vue()
Vue.prototype.$eventhande = hub //加入vue原型中,让所有组件可以访问到该对象

然后在定义一个兄弟组件brother.vue:

<template>
	<div>
		<h1>我是子组件的兄弟组件</h1>
		<button @click="todata">摁我传值给兄弟组件</button>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				brotherdata:"我是传给兄弟组件的数据"
			}
		},
		methods:{
			todata(){
//				触发自定义事件change,传入brotherdata值
				this.$eventhande.$emit('change',this.brotherdata)
			}
		}
	}
</script>

然后我们在另外一个兄弟组件接受该值就OK了,如图1和图2的father.vue,和son.vue

猜你喜欢

转载自blog.csdn.net/qq_39009348/article/details/81511981