defineExpose通俗來講,其實就是講子組件的方法或者數據,暴露給父組件進行使用,這樣對組件的封裝使用,有很大的幫助,那么defineExpose應該如何使用,下面我來用一些實際的代碼,帶大家快速學會defineExpose的使用
1.子組件:子組件有方法increaseCount,和數據count,現在我們將這他們全部暴露出去。
< template> < div> < h1> 子組件, 對defineExpose進行處理< / h1> < button @ click = "increaseCount" > Increase Count< / button> < p> Count: { { count } } < / p> < / div>
< / template> < script setup lang= "ts" >
import { ref } from 'vue' ; const count = ref ( 0 )
const increaseCount = ( ) => { count. value++ ;
} ;
defineExpose ( { count, increaseCount
} ) < / script>
< style scoped lang= "less" >
< / style>
2.父組件:我們為子組件定義ref為childexpose,這里有一個問題,如果這樣let childexpose = ref(null)聲明,ts會提示“childexpose.value”可能為 “null”。所以直接let childexpose = ref(),ts就不會報錯
在調用方法的時候,直接childexpose.value.increaseCount()就可以拿到他的方法,并且子組件的數據也會同步更新
< template> < div> < dExpose ref= "childexpose" > < / dExpose> < a- button type= "primary" status= "warning" @ click = "getChild" > Primary< / a- button> { { nums} } < / div>
< / template> < script setup lang= "ts" >
import { ref, onActivated } from "vue" ;
import dExpose from './components/defineExpose.vue' let nums = ref ( null )
let childexpose = ref ( )
const getChild = ( ) => { childexpose. value. increaseCount ( ) nums. value = childexpose. value. count
} < / script>
< style scoped lang= "less" >
ul { list- style- type: none; li { height: 30px; line- height: 30px; background- color: aqua; margin- bottom: 10px; }
}
< / style>