Vue父組件觸發(fā)子組件中的實(shí)現(xiàn)方法
有多種方法可以實(shí)現(xiàn)父組件觸發(fā)子組件中的方法,以下是其中兩種常用的方法:
1 通過 ref 取得子組件實(shí)例并調(diào)用方法
父組件可以在模板中通過 ref 給子組件命名,然后在父組件中使用 $refs 訪問子組件實(shí)例的方法。
<!-- 父組件 -->
<template>
<div>
<button @click="callChildMethod">調(diào)用子組件方法</button>
<child-component ref="child"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
this.$refs.child.childMethod(); //不傳參
this.$refs.child.childMethodParam(param); //可以直接向子組件傳遞參數(shù)param
}
}
}
</script>
在子組件中,需要在 methods 中定義要被調(diào)用的 childMethod 方法。
<!-- 子組件 -->
<template>
<div>
<!-- 組件內(nèi)容 -->
</div>
</template>
<script>
export default {
methods: {
childMethod() {
console.log('子組件方法被調(diào)用')
},
childMethodParam(param) {
console.log('子組件方法被調(diào)用,并接收到父組件傳遞過來的參數(shù):',param)
}
}
}
</script>2 使用自定義事件
父組件可以在需要觸發(fā)子組件中的方法的時(shí)候,通過 $emit 觸發(fā)自定義事件。然后在子組件中監(jiān)聽該事件,在事件回調(diào)函數(shù)中執(zhí)行對應(yīng)的方法。
<!-- 父組件 -->
<template>
<div>
<button @click="callChildMethod">調(diào)用子組件方法</button>
<child-component @custom-event="onCustomEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
this.$emit('custom-event')
},
onCustomEvent() {
console.log('custom-event 事件被觸發(fā)')
}
}
}
</script>
在子組件中,需要通過 props 來接收父組件傳遞的自定義事件,并在 created 生命周期中對其進(jìn)行監(jiān)聽。
<!-- 子組件 -->
<template>
<div>
<!-- 組件內(nèi)容 -->
</div>
</template>
<script>
export default {
props: ['customEvent'],
created() {
this.$on('custom-event', this.childMethod)
},
methods: {
childMethod() {
console.log('子組件方法被調(diào)用')
}
}
}
</script>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)滑塊拖拽校驗(yàn)功能的全過程
vue驗(yàn)證滑塊功能,在生活中很多地方都可以見到,使用起來非常方便,這篇文章主要給大家介紹了關(guān)于vue實(shí)現(xiàn)滑塊拖拽校驗(yàn)功能的相關(guān)資料,需要的朋友可以參考下2021-08-08
Vue 父子組件數(shù)據(jù)傳遞的四種方式( inheritAttrs + $attrs + $listeners)
這篇文章主要介紹了Vue 父子組件數(shù)據(jù)傳遞的四種方式( inheritAttrs + $attrs + $listeners),需要的朋友可以參考下2018-05-05
vue2.0實(shí)現(xiàn)選項(xiàng)卡導(dǎo)航效果
這篇文章主要為大家詳細(xì)介紹了vue2.0實(shí)現(xiàn)選項(xiàng)卡導(dǎo)航效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Vue3使用echarts tree高度自適應(yīng)支持滾動(dòng)查看功能
這篇文章主要介紹了Vue3使用echarts tree高度自適應(yīng)支持滾動(dòng)查看功能,文章同通過代碼示例介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-06-06
關(guān)于在vue-cli中使用微信自動(dòng)登錄和分享的實(shí)例
本篇文章主要介紹了關(guān)于在vue-cli中使用微信自動(dòng)登錄和分享的實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

