Vue子組件向父組件通信與父組件調(diào)用子組件中的方法
子組件向父組件通信
子組件的button按鈕綁定點擊事件,事件方法名為sendToParent(),
該方法在子組件的methods中聲明,實現(xiàn)功能this.$emit('cus-event',this.msg);
在父組件引入子組件,并給cus-event事件綁定doAction($event)方法,該方法中this.msg = e;console.log(e),
而msg已經(jīng)在data中聲明,其值為”子級消息”,故最終的輸出結(jié)果為: 展示父級接收到的消息:子級消息
父組件調(diào)用子組件中的方法
點擊父組件的button按鈕,觸發(fā)了click事件指向的useChild方法[該方法的行為是輸出”父級消息”],
useChild方法在父組件的中的methods中聲明,調(diào)用子組件中的方法,并傳入?yún)?shù)str,即this.$refs.child1.getMsg(str);
而getMsg方法已經(jīng)在子組件的methods中聲明,其行為是console.log
('子級組件收到父級的內(nèi)容',str);,
所以,最終的輸出結(jié)果為: 子級組件收到父級的內(nèi)容 父級消息
代碼示例(結(jié)合上面的分析理解代碼)
<!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)">調(diào)用子組件的方法</button> <!-- cus-event為子組件自定義的事件名; doAction($event)為父組件的事件,參數(shù)$event不可少也不可寫成其他--> <!-- ref表示組件的別名 --> <child @cus-event="doAction($event)" ref="child1"></child> </div> </body> </html> <template id="child"> <div id="wrapper"> <!-- 子組件 --> <h2>這是子組件</h2> <button @click="sendToParent">向父組件發(fā)消息</button> </div> </template> <script> let child = { template: '#child', data() { return { msg: '子級消息' }; }, methods: { sendToParent() { // 子組件只管發(fā)送消息,其中cus-event為自定義事件名(事件名不能寫成駝峰法,多個單詞用-連接),this.msg為要傳遞的參數(shù)。 this.$emit('cus-event', this.msg); }, getMsg(str) { console.log('子級組件收到父級的內(nèi)容', str); } } }; // 注意: .$mount('#app')跟實例內(nèi)部el: '#app'是等價的 new Vue({ data: { msg: '', szStr:'父級消息' }, components: { child }, methods: { doAction(e) { console.log(this); console.log(e); this.msg = e; }, useChild(str) { // 調(diào)用子組件的方法 // console.log(this); // console.log(this.$refs); // this.$refs.child1得到的子組件實例 this.$refs.child1.getMsg(str); } } }).$mount('#app'); </script>
效果圖
總結(jié)
以上所述是小編給大家介紹的Vue子組件向父組件通信與父組件調(diào)用子組件中的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue.js實現(xiàn)一個自定義分頁組件vue-paginaiton
這篇文章主要為大家詳細(xì)介紹了Vue.js實現(xiàn)一個自定義分頁組件vue-paginaiton的具體代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09Vue過渡效果之CSS過渡詳解(結(jié)合transition,animation,animate.css)
Vue 在插入、更新或者移除 DOM 時,提供多種不同方式的應(yīng)用過渡效果。本文將從CSS過渡transition、CSS動畫animation及配合使用第三方CSS動畫庫(如animate.css)這三方面來詳細(xì)介紹Vue過渡效果之CSS過渡2020-02-02Element-UI Table組件上添加列拖拽效果實現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了Element-UI Table組件上添加列拖拽效果的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04