Vue中兄弟组件之间进行通信
1、 先将组件1的数据传给父组件
//组件1中定义方法send()将数据传给父组件
send(){
this.$emit('data-msg',this.message);
}
// 父组件通过定义事件响应获取组件1数据
@data-msg="msg2($event)"
msg2(message){
console.log(message);
this.msgbro2 = message;
}
-->
2、 再将父组件的数据传给组件2
props属性获取父组件传入数据
props: {
msgbro2: {
type: String,
default: ''
}
}
App.vue
<template>
<div id="app">
<brother1 @data-msg="msg2($event)"></brother1>
<brother2 :msgbro2="msgbro2"></brother2>
</div>
</template>
<script>
import Brother1 from "./components/Brother1";
import Brother2 from "./components/Brother2";
export default {
name: 'app',
data() {
return {
msgbro2:'',
}
},
components: {
Brother1,
Brother2
},
methods: {
msg2(message){
console.log(message);
this.msgbro2 = message;
}
}
}
</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>
Brother1.vue
<template>
<div id="b1">
<h2>我是组件1</h2>
<button @click="send">点击我:将数据发送个Brother2组件</button>
</div>
</template>
<script>
export default {
name: "Brother1",
data(){
return {
message:'我是组件1数据',
}
},
methods: {
send(){
this.$emit('data-msg',this.message);
}
}
}
</script>
<style scoped>
</style>
Brother2.vue
<template>
<div id="b2">
<h2>我是组件2</h2>
<p>{
{
msgbro2}}<p/>
</div>
</template>
<script>
export default {
name: "Brother2",
props: {
msgbro2: {
type: String,
default: ''
}
}
}
</script>
<style scoped>
</style>