国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vue子組件向父組件通信與父組件調用子組件中的方法

2019-11-19 13:37:08
字體:
來源:轉載
供稿:網友

子組件向父組件通信

子組件的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> 

效果圖

總結

以上所述是小編給大家介紹的Vue子組件向父組件通信與父組件調用子組件中的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临安市| 通许县| 房产| 元阳县| 安阳市| 民权县| 宁海县| 陇南市| 电白县| 庆安县| 南安市| 米脂县| 杭锦后旗| 荥阳市| 凯里市| 金堂县| 南江县| 将乐县| 石河子市| 崇礼县| 巴中市| 乳源| 湖南省| 汽车| 那曲县| 长岭县| 郓城县| 荥阳市| 昌图县| 扬中市| 祁门县| 金门县| 明水县| 合山市| 靖江市| 鄄城县| 怀宁县| 辉南县| 深泽县| 乌拉特中旗| 侯马市|