Vue3.js調用父組件的實現方式
更新時間:2025年10月10日 08:42:01 作者:丨404 NotFound
這篇文章主要介紹了Vue3.js調用父組件的實現方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Vue3.js調用父組件
Vue2的時候一直使用this.$emit('方法名','參數')的方式, 調用父組件的方法. 是沒有問題的.
Vue3的時候, 假如我們父組件的方法放在setup()函數中, 子組件是無法獲取通過this.$emit()調用父組件的方法.
舉例代碼如下
- 父組件 Father.vue
<template>
<Child
@eventFuction="eventFuction"
>
</Child>
</template>
<script>
import { defineComponent } from 'vue'
import Child from "./Child.vue";
export default defineComponent({
name: "Father",
components: {
Child,
},
setup() {
// 父組件聲明的方法
const eventFuction = (param) =>{
console.log(param, '接收子組件傳值');
}
return {
eventFuction,
}
}
})
</script>
<style scoped>
</style>- 子組件 Child.vue
<template>
<a-button @click="onClick">調用父組件方法傳參</a-button>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: "Child",
setup() {
const onClick = ()=> {
// 這樣是會報錯的
this.$emit('eventFuction ', '10')
}
return{
onClick,
}
}
})
</script>
<style scoped>
</style>
原因分析
在vue3中setup是在聲明周期beforeCreate和created前執(zhí)行, 這時候vue對象還沒有創(chuàng)建, 所以我們無法使用this
解決辦法
子組件的setup()函數中有個context的參數,這個參數中包含了emit的方法。
配合這個我們可以調用父組件的方法。
- 子組件修改后代碼如下:
<template>
<a-button @click="onClick">調用父組件方法傳參</a-button>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: "Child",
setup(props, context) {
const onClick = ()=> {
// 這樣寫就沒問題了
context.emit('eventFuction ', '10')
}
return{
onClick,
}
}
})
</script>
<style scoped>
</style>總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue中使用 Echarts5.0 遇到的一些問題(vue-cli 下開發(fā))
這篇文章主要介紹了Vue中使用 Echarts5.0 遇到的一些問題(vue-cli 下開發(fā)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
openlayers6之地圖覆蓋物overlay三種常用用法(popup彈窗marker標注text文本)
這篇文章主要介紹了openlayers6之地圖覆蓋物overlay三種常用用法(popup彈窗marker標注text文本),主要講overlay三種最常用的案例,感興趣的朋友一起看看吧2021-09-09

