vue3通過ref獲取子組件defineExpose的數據和方法
更新時間:2023年10月09日 09:29:34 作者:qq_42750608
defineExpose是Vue3中新增的選項,用于向父組件暴露子組件內部的屬性和方法,通過defineExpose,子組件可以主動控制哪些屬性和方法可以被父組件訪問,本文主要介紹了vue3通過ref獲取子組件defineExpose的數據和方法,需要的朋友可以參考下
1. 父組件:
<script setup> import { defineAsyncComponent, watchEffect, toRefs, reactive } from 'vue'; // 異步組件 const Test = defineAsyncComponent(()=>import('./xx/Test.vue')) const child1Ref = ref(null) const state = reactive({ age: 1, name: '2', sayHello: null, }) watchEffect(() => { // 拿到子組件的一些數據 console.log(child1Ref.value) const obj = toRefs(child1Ref.value) console.log(obj.a, obj.b) state.name = obj.b state.age = obj.a state.sayHello = obj.onSayHello }) </script> <template> {{ state.age }} -- {{ state.name }} <button @click="state.sayHello">say hello</button> <Test ref="child1Ref"/> </template>
2. 子組件
<script setup> import { ref, defineExpose } from 'vue' const a = ref(101) const b = ref('sddewfewfew') const onSayHello = () => { console.log('hello') } defineExpose({ a, b, onSayHello, }) </script> <template> <p>Child1</p> </template>
到此這篇關于vue3通過ref獲取子組件defineExpose的數據和方法的文章就介紹到這了,更多相關vue3獲取defineExpose內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Element中table組件(el-table)右側滾動條空白占位處理
當我設置了max-height,就會在表格右側出現一列空白的占位,本文主要介紹了Element中table組件(el-table)右側滾動條空白占位處理,感興趣的可以了解一下2023-09-09vue+element-ui+sortable.js實現表格拖拽功能
這篇文章主要為大家詳細介紹了vue+element-ui+sortable.js實現表格拖拽功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04