vue3
中默認父組件通過ref
綁定子組件是獲取不到子組件中的dom
和變量、方法的,子組件需要通過defineExpose
方法把需要暴露的東西暴露出去,父組件才能拿的到,實例演示一下:
子組件 Child.vue
<template>
<div>
<input type="text" v-model="content" />
</div>
</template>
<script lang='ts' setup>
import { ref } from 'vue'
const content = ref('')
</script>
父組件 Father.vue
<template>
<div>
<Child ref='rChild' />
</div>
</template>
<script lang='ts' setup>
import { ref,onMounted } from 'vue'
import Child from './Child.vue'
const rChild= ref(null)
onMounted(()=>{
console.log(rChild.value)
})
</script>
打印出來是一個
proxy
對象,里面拿不到子組件的任何信息,通過defineExpose
改造一下子組件,即可能拿到子組件里面的內容
改造子組件 Child.vue
<template>
<div ref='rInput'>
<input type="text" v-model="content" />
</div>
</template>
<script lang='ts' setup>
import { ref } from 'vue'
const content = ref('')
const rInput = ref(null)
defineExpose({rInput,content })
</script>
通過上面的子組件的改造,那父組件就可以通過
rChild.value.content
和rChild.value.rInput
拿到子組件中的content
的變量及dom
結構。