在Vue3中窿凤,父組件可通過創(chuàng)建一個ref(null),然后將賦值的元素寫在當(dāng)前子組件上即可屯仗,在需要的時候送朱,通過定義的響應(yīng)式變量即可獲取娘荡,獲取后即可取得當(dāng)前子組件內(nèi)部dom以及當(dāng)前子組件內(nèi)部變量方法等,并且直接使用子組件內(nèi)部方法骤菠。但是有時候獲取的時候返回的沒有什么信息只有一個{_v_skin:true}
這個信息,這條信息表示數(shù)據(jù)無法響應(yīng)疤孕。
父組件示例
<template>
<div class="container">
<h-demo ref="childDom" />
<button @click="getChild"></button>
</div>
</template>
<script>
import Hdemo from '@/components/Hdemo';
import { ref } from 'vue';
export default {
components:{
'h-demo':Hdemo
},
setup(){
const childDom=ref(null)
const getChild = () =>{
console.log(childDom.value)
// 打印當(dāng)前子組件暴露出來的數(shù)據(jù)
childDom.value.handleVal()
// 執(zhí)行子組件方法
}
return {
childDom,
getChild
}
}
}
</script>
<style lang="scss" scoped>
</style>
子組件示例
<script setup>
import { ref } from 'vue';
const demo=ref('測試用例')
const handleVal=()=>{
demo.value="已改變"
}
</script>
<template>
<div class="inner">
{{demo}}
<button @click="handleVal">改值</button>
</div>
</template>
<style lang="scss" scoped>
</style>
此時childDom.value的值為{_v_skin:true}無法獲取子組件內(nèi)部信息
重點
原因:使用 <script setup> 語法糖的組件是默認(rèn)關(guān)閉的商乎,也即通過模板 ref 或者 $parent 鏈獲取到的組件的公開實例,不會暴露任何在 <script setup> 中聲明的綁定祭阀。
方法:為了在 <script setup> 語法糖組件中明確要暴露出去的屬性鹉戚,,使用 defineExpose 編譯器宏將需要暴露出去的變量與方法放入暴露出去就可以
子組件使用defineExpose 暴露示例
<script setup>
import { ref } from 'vue';
const demo=ref('測試用例')
const handleVal=()=>{
demo.value="已改變"
}
//將需要暴露出去的數(shù)據(jù)與方法都可以暴露出去
defineExpose({
demo,
handleVal,
})
</script>
<template>
<div class="inner">
{{demo}}
<button @click="handleVal">改值</button>
</div>
</template>
<style lang="scss" scoped>
</style>
此時父組件即可獲取子組件內(nèi)部變量與方法與當(dāng)前dom等信息