兄弟有共同的父级
创建child-a.vue
<template>
<div>
我是child - a组件
</div>
</template>
创建child-b.vue
<template>
<div>
我是child - b组件
</div>
</template>
创建parent.vue
<template>
<div>
<h1>我是父组件</h1>
<hr>
<!-- 这里要调用子组件 -->
<child-a />
<child-b />
</div>
</template>
<script>
// 第一步:导入组件
import ChildA from './child-a'
import ChildB from './child-b'
export default {
// 第二步:注册组件
components: {
ChildA,
ChildB
}
}
</script>
通信思路: 先把a的数据传递给parent
<!-- child-a.vue -->
<template>
<div>
我是child - a组件
<a href="JavaScript:;" @click="send">点我把数据传递给我的老弟b</a>
</div>
</template>
<script>
export default {
data() {
return {
msg: '我是子组件-a的数据'
}
},
methods: {
send() {
this.$emit('customEvent', this.msg)
}
}
}
</script>
在parent组件接收a组件传递过来的数据
<!-- parent.vue -->
<template>
<div>
<h1>我是父组件</h1>
<hr>
<!-- 这里要调用子组件 -->
<child-a @customEvent="parentReceive" />
<child-b />
</div>
</template>
<script>
// 第一步:导入组件
import ChildA from './child-a'
import ChildB from './child-b'
export default {
// 第二步:注册组件
components: {
ChildA,
ChildB
},
methods: {
parentReceive(val) {
console.log(val)
}
}
}
</script>
父组件中转一下
<template>
</template>
<script>
// 第一步:导入组件
import ChildA from './child-a'
import ChildB from './child-b'
export default {
data() {
return {
childVal: ''
}
},
methods: {
parentReceive(val) {
// 中转一下
this.childVal = val
}
}
}
</script>
父组件parent传递给b组件
<child-b :title="childVal" />
b组件接收
<template>
<div>
我是child - b组件:{{ title }}
</div>
</template>
<script>
export default {
props: ['title']
}
</script>
总结:
-
子(a)传父(parent)(this.$emit)
-
父(parent)定义一个变量进行接收子(a)传递过来的数据(中转)
-
父(parent)传子(b)(props)