vue3?setup中父組件通過Ref調(diào)用子組件的方法(實例代碼)
在setup()鉤子函數(shù)中調(diào)用
父組件
<template> <div> 我是父組件 <children ref="childrenRef" /> <button @click="handleChildren">觸發(fā)子組件</button> </div> </template> <script lang="ts"> import { ref, defineComponent } from 'vue' import Children from './components/Children.vue'; export default defineComponent({ components: { Children } setup() { // ref的泛型除了指定any外 還可以指定<InstanceType<typeof Children>> const childrenRef = ref<any>(); const handleChildren = () => childrenRef.value.isChildren(); return { childrenRef, handleChildren } }, }) </script>
子組件:
<template> <div> 我是子組件 </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ setup() { const isChildren = () => { console.log("我是子組件"); } return { isChildren, } } }) </script>
如果是在setup()
鉤子函數(shù)中使用,父組件通過ref
獲取到子組件實例后,直接.value.函數(shù)名
即可調(diào)用子組件所定義的函數(shù)。其中ref的泛型可以指定any
和InstanceType<typeof Children>
在<srcipt setup>中調(diào)用
父組件
<template> <div> 我是子組件 </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ setup() { const isChildren = () => { console.log("我是子組件"); } return { isChildren, } } }) </script>
子組件
<template> <div> 我是子組件 </div> </template> <script setup lang="ts"> import { defineExpose } from 'vue'; const isChildren = () => { console.log("我是子組件的第一個方法"); } const isChildren2 = () => { console.log("我是子組件的第二個方法"); } defineExpose({ isChildren, isChildren2 }) </script>
在<srcipt setup>
中調(diào)用和setup()
鉤子函數(shù)中調(diào)用不同的是:子組件中要通過defineExpose
將方法暴露給父組件。
到此這篇關(guān)于vue3 setup中父組件通過Ref調(diào)用子組件的方法的文章就介紹到這了,更多相關(guān)vue3 setup父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue.js+HighCharts實現(xiàn)動態(tài)請求展示時序數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了Vue.js+HighCharts實現(xiàn)動態(tài)請求展示時序數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03vue3.2?reactive函數(shù)問題小結(jié)
reactive用來包裝一個對象,使其每個對象屬性都具有響應(yīng)性(也就是深層次響應(yīng)式),這篇文章主要介紹了vue3.2?reactive函數(shù)注意點及問題小結(jié),需要的朋友可以參考下2022-12-12Vue實現(xiàn)省市區(qū)三級聯(lián)動el-select組件的示例代碼
這篇文章主要為大家詳細(xì)介紹了Vue實現(xiàn)省市區(qū)三級聯(lián)動el-select組件的方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,需要的的可以參考一下2023-02-02vue實現(xiàn)導(dǎo)出Word文件(數(shù)據(jù)流方式)
這篇文章主要介紹了vue實現(xiàn)導(dǎo)出Word文件(數(shù)據(jù)流方式),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例
這篇文章主要介紹了Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08