Skip to content

Commit e3f6ad8

Browse files
committed
补全常见组件通信手段
1 parent 1b128bc commit e3f6ad8

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/components/communication/Child1.vue

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,14 @@
1414
},
1515
},
1616
mounted () {
17-
this.$bus.$on('event-from-child2', msg => {
17+
// 总线方式通信
18+
// this.$bus.$on('event-from-child2', msg => {
19+
// console.log('Child1:', msg);
20+
// });
21+
22+
// 利用共同祖辈方式通信
23+
// 兄弟组件可以使用$parent, 没有直接关系使用$root
24+
this.$parent.$on('event-from-child2', msg => {
1825
console.log('Child1:', msg);
1926
});
2027
},

src/components/communication/Child2.vue

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
methods: {
1111
sendToChild1() {
1212
// 利用事件总线发送事件
13-
this.$bus.$emit('event-from-child2', 'some msg from child2')
13+
// this.$bus.$emit('event-from-child2', 'some msg from child2')
14+
// 利用共同祖辈元素发送事件
15+
this.$parent.$emit('event-from-child2', 'some msg from child2')
1416
}
1517
},
1618
}

src/components/communication/index.vue

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<!-- props, 自定义事件 -->
55
<Child1 msg="some msg from parent" @some-event="onSomeEvent"></Child1>
66
<!-- 事件总线 -->
7-
<Child2></Child2>
7+
<Child2 ref="child2"></Child2>
88
</div>
99
</template>
1010

@@ -21,6 +21,13 @@
2121
console.log('Communition:', msg);
2222
}
2323
},
24+
mounted () {
25+
// $children获取子组件数组,不包括普通元素,不保证模板中顺序
26+
console.log(this.$children);
27+
// $refs用于引用命名的元素或组件,可包含普通元素
28+
console.log(this.$refs.child2);
29+
30+
},
2431
}
2532
</script>
2633

0 commit comments

Comments
 (0)