子組件向父組件通信
子組件的button按鈕綁定點擊事件,事件方法名爲sendToParent(),
該方法在子組件的methods中聲明,實現功能this.$emit('cus-event',this.msg);
在父組件引入子組件,並給cus-event事件綁定doAction($event)方法,該方法中this.msg = e;console.log(e),
而msg已經在data中聲明,其值爲”子級消息”,故最終的輸出結果爲: 展示父級接收到的消息:子級消息
父組件調用子組件中的方法
點擊父組件的button按鈕,觸發了click事件指向的useChild方法[該方法的行爲是輸出”父級消息”],
useChild方法在父組件的中的methods中聲明,調用子組件中的方法,並傳入參數str,即this.$refs.child1.getMsg(str);
而getMsg方法已經在子組件的methods中聲明,其行爲是console.log('子級組件收到父級的內容',str);,
所以,最終的輸出結果爲: 子級組件收到父級的內容 父級消息
代碼示例(結合上面的分析理解代碼)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>子向父通信</title>
<style>
#app {
border: 1px solid blue;
width: 500px;
padding: 20px;
margin: auto;
border-radius: 8px;
background: fuchsia;
}
#wrapper {
border: 1px solid red;
width: 400px;
padding: 20px;
border-radius: 8px;
background: yellowgreen;
margin-top: 20px;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<!-- 父組件 -->
<h1>這是父組件</h1>
<p>展示父級接收到的消息:{{msg}}</p>
<button @click="useChild(szStr)">調用子組件的方法</button>
<!-- cus-event爲子組件自定義的事件名; doAction($event)爲父組件的事件,參數$event不可少也不可寫成其他-->
<!-- ref表示組件的別名 -->
<child @cus-event="doAction($event)" ref="child1"></child>
</div>
</body>
</html>
<template id="child">
<div id="wrapper">
<!-- 子組件 -->
<h2>這是子組件</h2>
<button @click="sendToParent">向父組件發消息</button>
</div>
</template>
<script>
let child = {
template: '#child',
data() {
return {
msg: '子級消息'
};
},
methods: {
sendToParent() {
// 子組件只管發送消息,其中cus-event爲自定義事件名(事件名不能寫成駝峯法,多個單詞用-連接),this.msg爲要傳遞的參數。
this.$emit('cus-event', this.msg);
},
getMsg(str) {
console.log('子級組件收到父級的內容', str);
}
}
};
// 注意: .$mount('#app')跟實例內部el: '#app'是等價的
new Vue({
data: {
msg: '',
szStr:'父級消息'
},
components: {
child
},
methods: {
doAction(e) {
console.log(this);
console.log(e);
this.msg = e;
},
useChild(str) {
// 調用子組件的方法
// console.log(this);
// console.log(this.$refs);
// this.$refs.child1得到的子組件實例
this.$refs.child1.getMsg(str);
}
}
}).$mount('#app');
</script>
效果圖