Vue3.js調(diào)用父組件的實(shí)現(xiàn)方式
Vue3.js調(diào)用父組件
Vue2的時候一直使用this.$emit('方法名','參數(shù)')的方式, 調(diào)用父組件的方法. 是沒有問題的.
Vue3的時候, 假如我們父組件的方法放在setup()函數(shù)中, 子組件是無法獲取通過this.$emit()調(diào)用父組件的方法.
舉例代碼如下
- 父組件 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">調(diào)用父組件方法傳參</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()函數(shù)中有個context的參數(shù),這個參數(shù)中包含了emit的方法。
配合這個我們可以調(diào)用父組件的方法。
- 子組件修改后代碼如下:
<template>
<a-button @click="onClick">調(diào)用父組件方法傳參</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>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vux+Axios攔截器增加loading的問題及實(shí)現(xiàn)方法
這篇文章主要介紹了Vux+Axios攔截器增加loading的問題及實(shí)現(xiàn)方法,文中通過實(shí)例代碼介紹了vue中使用axios的相關(guān)知識,需要的朋友可以參考下2018-11-11
element-plus中el-upload組件限制上傳文件類型的方法
?Element Plus 中,el-upload 組件可以通過設(shè)置 accept 屬性來限制上傳文件的格式,這篇文章主要介紹了element-plus中el-upload組件限制上傳文件類型,需要的朋友可以參考下2024-02-02
vue實(shí)現(xiàn)數(shù)字變換動畫的示例代碼
本文主要介紹了vue實(shí)現(xiàn)數(shù)字變換動畫的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
vue實(shí)現(xiàn)input框禁止輸入標(biāo)簽
這篇文章主要介紹了vue實(shí)現(xiàn)input框禁止輸入標(biāo)簽,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue3中使用styled-components的實(shí)現(xiàn)
本文主要介紹了Vue3中使用styled-components的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
vue?element修改el-select控件長度style=“width:XXpx“不生效的解決
這篇文章主要介紹了vue?element修改el-select控件長度style=“width:XXpx“不生效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

