Vue中子組件調(diào)用父組件的3種方法實(shí)例
Vue中子組件調(diào)用父組件的三種方法:
1.直接在子組件中通過“this.$parent.event”來調(diào)用父組件的方法。
父組件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from './components/childcomponent';
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>
2.子組件用“$emit”向父組件觸發(fā)一個事件,父組件監(jiān)聽這個事件即可。
父組件
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './components/childcomponent'
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>
3.父組件把方法傳入子組件中,在子組件里直接調(diào)用這個方法即可。
父組件
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './components/childcomponent';
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() {
this.fatherMethod();
}
}
}
};
</script>總結(jié)
到此這篇關(guān)于Vue中子組件調(diào)用父組件的3種方法的文章就介紹到這了,更多相關(guān)Vue子組件調(diào)用父組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中使用Cesium加載shp文件、wms服務(wù)、WMTS服務(wù)問題
這篇文章主要介紹了vue中使用Cesium加載shp文件、wms服務(wù)、WMTS服務(wù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
vue3.0中ref與reactive的區(qū)別及使用場景分析
ref與reactive都是Vue3.0中新增的API,用于響應(yīng)式數(shù)據(jù)的處理,這篇文章主要介紹了vue3.0中ref與reactive的區(qū)別及使用,需要的朋友可以參考下2023-08-08
Vue3之Mixin的使用方式(全局,局部,setup內(nèi)部使用)
這篇文章主要介紹了Vue3之Mixin的使用方式(全局,局部,setup內(nèi)部使用),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Vue自定義組件實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定的方法
這篇文章主要介紹了Vue自定義組件實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定的方法,文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-11-11
Vue3?中的?readonly?特性及函數(shù)使用詳解
readonly是Vue3中提供的一個新特性,用于將一個響應(yīng)式對象變成只讀對象,這篇文章主要介紹了Vue3?中的?readonly?特性詳解,需要的朋友可以參考下2023-04-04
Element-UI中<el-cascader?/>回顯失敗問題的完美解決
我們在使用el-cascader控件往數(shù)據(jù)庫保存的都是最后一級的數(shù)據(jù),那如果再次編輯此條數(shù)據(jù)時,直接給el-cascader傳入最后一級的數(shù)據(jù),它是不會自動勾選的,下面這篇文章主要給大家介紹了關(guān)于Element-UI中<el-cascader?/>回顯失敗問題的完美解決辦法,需要的朋友可以參考下2023-01-01
element 穿梭框性能優(yōu)化的實(shí)現(xiàn)
本文主要介紹了element 穿梭框性能優(yōu)化,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10

