Vue子組件調(diào)用父組件方法案例詳解
更新時間:2021年09月14日 09:03:25 作者:貓老板的豆
這篇文章主要介紹了Vue子組件調(diào)用父組件方法案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
一、直接在子組件中通過this.$parent.event來調(diào)用父組件的方法
<!-- 父組件 --> <template> <div> <child></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod () { console.log('測試'); } } }; </script>
<!-- 子組件 --> <template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script>
二、在子組件里用$emit向父組件觸發(fā)一個事件,父組件監(jiān)聽這個事件
<!-- 父組件 --> <template> <div> <child @fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod () { console.log('測試'); } } }; </script>
<!-- 子組件 --> <template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { methods: { childMethod () { this.$emit('fatherMethod'); } } }; </script>
三、父組件把方法傳入子組件中,在子組件里直接調(diào)用這個方法
<!-- 父組件 --> <template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod () { console.log('測試'); } } }; </script>
<!-- 子組件 --> <template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod () { if (this.fatherMethod) { this.fatherMethod(); } } } }; </script>
到此這篇關(guān)于Vue子組件調(diào)用父組件方法案例詳解的文章就介紹到這了,更多相關(guān)Vue子組件調(diào)用父組件方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue+vant-UI框架實(shí)現(xiàn)購物車的復(fù)選框全選和反選功能
這篇文章主要介紹了vue+vant-UI框架實(shí)現(xiàn)購物車的復(fù)選框全選和反選功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11vue微信分享出來的鏈接點(diǎn)開是首頁問題的解決方法
這篇文章主要為大家詳細(xì)介紹了vue微信分享出來的鏈接點(diǎn)開是首頁問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11Vue中使用clipboard實(shí)現(xiàn)復(fù)制功能
這篇文章主要介紹了Vue中結(jié)合clipboard實(shí)現(xiàn)復(fù)制功能 ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09詳解vue項(xiàng)目中使用token的身份驗(yàn)證的簡單實(shí)踐
這篇文章主要介紹了vue項(xiàng)目中使用token的身份驗(yàn)證的簡單實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Vue.js+Layer表格數(shù)據(jù)綁定與實(shí)現(xiàn)更新的實(shí)例
下面小編就為大家分享一篇Vue.js+Layer表格數(shù)據(jù)綁定與實(shí)現(xiàn)更新的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03