vue3 ref獲取不到子組件的解決方法
需求
在父組件內調用子組件內的事件從而改變子組件的某些狀態(tài),父子組件使用<script setup>
語法糖,父組件通過給子組件定義ref訪問其內部事件。這看起來完全沒毛病,理想很豐滿,現(xiàn)實很骨感,寫完就是訪問不到,還報錯,離離原上譜,這究竟是為啥
經過一番調查,我才明白setup語法糖需要用defineExpose把要讀取的屬性和方法單獨暴露出去
,這就不得不反思一下自己當初是怎么學習的使用setup語法糖,回想好像只是在查閱資料時看到有人貼了一段代碼是這樣方式就直接照貓畫虎的直接使用,根本沒有去查閱官方文檔去細致全面的學習,呼倫吞棗是真的會挖很多坑等待自己探索
下面我做了一個測試,我創(chuàng)建兩個子組件,一個使用setup語法糖,另一個使用setup()函數,都在父組件通過ref去訪問,打印看結果
父組件:HomeView.vue
<template> <div class="home"> <myChild ref="child" /> <myChild2 ref="child2" /> <button @click="add">點擊</button> </div> </template> <script setup> import myChild from './myChild.vue' import myChild2 from './myChild2.vue' import { ref } from 'vue' const child = ref(null) const child2 = ref(null) const add = () => { console.log('child=>', child.value, '========', 'child2=>', child2.value) // child.value.insert() // child2.value.insert() } </script>
子組件1:myChild.vue
<template> <div class="about"> <h1 @click="insert">myChild:{{ num }}</h1> </div> </template> <script setup> import { ref } from 'vue' const num = ref(0) const insert = () => { num.value++ } </script>
子組件2:myChild2.vue
<template> <div class="about"> <h1 @click="insert">myChild2:{{ num }}</h1> </div> </template> <script> import { ref } from 'vue' export default { setup () { const num = ref(0) const insert = () => { num.value++ } return { num, insert } } } </script>
結果
從下圖結果可以看出,可以通過ref訪問myChild2組件,但是無法訪問myChild組件,
原因
vue3項目使用<script setup>
語法糖相比于使用setup()
函數會更加方便簡潔,但前者會將組件私有化
,也就是說使用<script setup>的組件中的數據和事件無法被外部訪問
,此時父組件就無法通過ref去訪問該子組件。
除非主動對外暴露 setup 中的數據和方法,使用 defineExpose
API,此時你可以向外暴露任何你允許外部訪問的
<!-- myChild --> <script setup> import { ref, defineExpose } from 'vue' const num = ref(0) const insert = () => { num.value++ } // 向外暴露 insert 事件 defineExpose({ insert, a: 1, b: 2 }) </script>
到此這篇關于vue3 ref獲取不到子組件的解決方法的文章就介紹到這了,更多相關vue3 ref獲取不到子組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue如何使用element ui表格el-table-column在里面做判斷
這篇文章主要介紹了vue如何使用element ui表格el-table-column在里面做判斷問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08Vue中this.$refs獲取為undefined的原因和解決辦法(this.$refs.屬性為undefined原因
在Vue項目開發(fā)中,使用this.$refs訪問組件或DOM元素的引用時,可能會遇到獲取為undefined的情況,這篇文章主要介紹了Vue中this.$refs獲取為undefined的原因和解決辦法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-11-11