Vue子組件調(diào)用父組件方法案例詳解
一、直接在子組件中通過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中使用EventBus實現(xiàn)組件間的高效通信
在現(xiàn)代前端開發(fā)中,Vue.js?作為一種流行的漸進(jìn)式框架,廣泛應(yīng)用于各類?Web?項目的構(gòu)建中,本文將深入探討如何在?Vue?中使用?EventBus,實現(xiàn)組件間的高效通信,需要的可以了解下2024-11-11
關(guān)于vue.js中實現(xiàn)方法內(nèi)某些代碼延時執(zhí)行
今天小編就為大家分享一篇關(guān)于vue.js中實現(xiàn)方法內(nèi)某些代碼延時執(zhí)行,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Vue2.0使用過程常見的一些問題總結(jié)學(xué)習(xí)
本篇文章主要介紹了Vue2.0使用過程常見的一些問題總結(jié)學(xué)習(xí),詳細(xì)的介紹了使用中會遇到的各種錯誤,有興趣的可以了解一下。2017-04-04
vue-cli3使用postcss-plugin-px2rem方式
這篇文章主要介紹了vue-cli3使用postcss-plugin-px2rem方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例
這篇文章主要介紹了Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue監(jiān)聽瀏覽器網(wǎng)頁關(guān)閉和網(wǎng)頁刷新事件代碼示例
在前端開發(fā)中我們通常會遇到這樣的需求,用戶離開、刷新頁面前,修改數(shù)據(jù)未進(jìn)行保存操作,需要提示框提醒用戶,這篇文章主要給大家介紹了關(guān)于vue監(jiān)聽瀏覽器網(wǎng)頁關(guān)閉和網(wǎng)頁刷新事件的相關(guān)資料,需要的朋友可以參考下2023-08-08

