一、父组件给子组件传值:prop

1、父组件部分:
在调用子组件的时候,使用 v-bind 将 msg 的值绑定到子组件上:parentMsg=“msg”

<child-component  :parentMsg="msg"></child-component>
//引入子组件
import childComponent form '@component/childComponent'

export default{
	//注册子组件
	components:{
		childComponent: childComponent 
	},
	data(){
		return{
			//要传递给子组件的数据
			msg: '从父组件传过来的值parentMsg'
		}
	}
}

2、子组件部分:

用props来接收父组件传过来的值

<template>
	<div>
		{{parentMsg}}
	</div>
</template>
export default{
	name:'childComponent',
	props:['parentMsg']
}

二、子组件给父组件传值:this.$emit

1、子组件部分:
子组件主要通过事件传递数据给父组件

<template>
	<div>
		<div @click="childEvent"></div>
	</div>
</template>
export default{
	name:'childComponent',
	methods:{
		childEvent(){
			this.$emit('childEvent', '从子组件传过来的参数childMsg');
			//this.$emit('与在父组件中子组件调用的地方自定义的事件名一致','要传递的值1','要传递的值2',...)
		}
	}
}

2、父组件部分:

声明了一个方法 getChildMsg,用 childEvent自定义 事件调用 getChildMsg方法,获取到从子组件传递过来的参数

<child-component  @childEvent="getChildMsg"></child-component>
//引入子组件
import childComponent form '@component/childComponent'

export default{
	//注册子组件
	components:{
		childComponent: childComponent 
	},
	data(){
		return{
			//要传递给子组件的数据
			msg: '从父组件传过来的值parentMsg'
		}
	},
	methods:{
		getChildMsg(msg){
			console.log(msg);//从子组件传过来的参数childMsg
		}
	}
}

3、父组件调用子组件方法:ref

ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例:

<child-component ref="childComponent"></child-component>
this.$refs.childComponent.子组件的方法名(父组件给子组件传的参数);

三、兄弟组件之间的传值

兄弟组件之间的传值和子组件给父组件传值非常相似,都是用$emit。
原理:vue一个新的实例,相当于一个站,连接着两个组件,也就是一个中央事件总线。
第1步:创建一个bus实例eventBus.js:

import Vue from 'Vue'
export default new Vue

第2步:创建一个firdtChild.vue组件,引入bus,接着按绑定一个数据传输事件:$emit传输事件

<template>
	<div id="firstChild">
        <h2>firstChild组件</h2>
        <button @click="sendMes">向兄弟组件传值</button>
    </div>
</template>
<script>
    import bus from "./assets/eventBus"
	export default{
        methods:{
            sendMes:function(){
            	//传输的事件名和参数
                bus.$emit("userDefindEvent","这是传输的信息,哈哈哈哈哈");
            }
        }
    }
</script>

第3步:创建另一个组件secondChild.vue,引入bus实例:$on接收事件;

<template>
	<div id="secondChild">
        <h2>secondChild组件</h2>
        <p>从firstChild传过来的参数:{{msg}}</p>
    </div>
</template>
<script>
    import bus from "./assets/eventBus";
	export default{
        data(){
            return:{
                msg:''
            }
        },
        mouted(){
            var self = this;
            bus.$on("userDefindEvent",function(sendMsg){
                //此处的事件名,与firstChild.vue定义的事件名一致
                self.msg = sendMsg;
                console.log(self.msg);// --这是传输的信息,哈哈哈哈哈
            })
        }
    }
</script>