Vue子組件調(diào)用父組件方法案例詳解
更新時間:2021年09月14日 09:03:25 作者:貓老板的豆
這篇文章主要介紹了Vue子組件調(diào)用父組件方法案例詳解,本篇文章通過簡要的案例,講解了該項技術(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()">點擊</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()">點擊</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()">點擊</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框架實現(xiàn)購物車的復(fù)選框全選和反選功能
這篇文章主要介紹了vue+vant-UI框架實現(xiàn)購物車的復(fù)選框全選和反選功能,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11Vue中使用clipboard實現(xiàn)復(fù)制功能
這篇文章主要介紹了Vue中結(jié)合clipboard實現(xiàn)復(fù)制功能 ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09Vue.js+Layer表格數(shù)據(jù)綁定與實現(xiàn)更新的實例
下面小編就為大家分享一篇Vue.js+Layer表格數(shù)據(jù)綁定與實現(xiàn)更新的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03