兄弟組件通信的邏輯實現
注意: 藉助於一個公共的Vue的實例對象,不同的組件可以通過該對象完成事件的綁定和觸發.第一步: 在child1子組件中,給button按鈕綁定一個點擊事件toChild2, 在事件中我們通過公共的vue對象totalVm.$emit()方法去觸發一個定義事件event1,並傳遞我們的參數str.
第二步: 在child2組件創建的鉤子(created())中監聽事件event1, 並觸發回調函數fn1, fn1在methods中聲明,其行爲是輸出傳入的參數’hello world’
代碼示例(結合上面的分析理解代碼)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>兄弟通信</title>
<style>
#wrapper1,
#wrapper2 {
width: 300px;
padding: 20px;
border: 1px solid red;
border-radius: 8px;
margin: auto;
}
#wrapper1 {
margin-bottom: 20px;
border: 1px solid blue;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<child1></child1>
<child2></child2>
</div>
</body>
</html>
<!--子組件child1-->
<template id="child1">
<div id="wrapper1">
<h2>子組件1</h2>
<button @click="toChild2('hello world')">向child2發消息</button>
</div>
</template>
<!--子組件child2-->
<template id="child2">
<div id="wrapper2">
<h2>子組件2</h2>
<p>顯示child1傳過來的內容:{{greeting}}</p>
</div>
</template>
<script>
let totalVm = new Vue();
let child1 = {
template: '#child1',
methods: {
toChild2(str) {
// 發消息都是通過viewmodel的實例對象發送的
totalVm.$emit('event1', str);
}
}
};
let child2 = {
template: '#child2',
created() {
totalVm.$on('event1', this.fn1);
},
data() {
return {
greeting: ''
}
},
methods: {
fn1(str) {
console.log("子組件2收到子組件1的消息",str);
this.greeting = str;
}
}
};
new Vue({
el: '#app',
data: {},
components: {
child1,
child2
},
created() {
// 只要實例監聽到該事件,當有組件發送($emit)時,就會觸發回調函數
totalVm.$on('event1', (str) => {
console.log('父級接收到的消息:', str)
});
}
});
</script>
效果圖