欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3 ref獲取不到子組件的解決方法

 更新時(shí)間:2024年06月18日 11:01:27   作者:麻辣翅尖  
在父組件內(nèi)調(diào)用子組件內(nèi)的事件從而改變子組件的某些狀態(tài),父子組件使用<script setup>語(yǔ)法糖,父組件通過(guò)給子組件定義ref訪(fǎng)問(wèn)其內(nèi)部事件,本文給大家介紹了vue3 ref獲取不到子組件的解決方法,需要的朋友可以參考下

需求

在父組件內(nèi)調(diào)用子組件內(nèi)的事件從而改變子組件的某些狀態(tài),父子組件使用<script setup>語(yǔ)法糖,父組件通過(guò)給子組件定義ref訪(fǎng)問(wèn)其內(nèi)部事件。這看起來(lái)完全沒(méi)毛病,理想很豐滿(mǎn),現(xiàn)實(shí)很骨感,寫(xiě)完就是訪(fǎng)問(wèn)不到,還報(bào)錯(cuò),離離原上譜,這究竟是為啥

在這里插入圖片描述

經(jīng)過(guò)一番調(diào)查,我才明白setup語(yǔ)法糖需要用defineExpose把要讀取的屬性和方法單獨(dú)暴露出去,這就不得不反思一下自己當(dāng)初是怎么學(xué)習(xí)的使用setup語(yǔ)法糖,回想好像只是在查閱資料時(shí)看到有人貼了一段代碼是這樣方式就直接照貓畫(huà)虎的直接使用,根本沒(méi)有去查閱官方文檔去細(xì)致全面的學(xué)習(xí),呼倫吞棗是真的會(huì)挖很多坑等待自己探索

下面我做了一個(gè)測(cè)試,我創(chuàng)建兩個(gè)子組件,一個(gè)使用setup語(yǔ)法糖,另一個(gè)使用setup()函數(shù),都在父組件通過(guò)ref去訪(fǎng)問(wèn),打印看結(jié)果

父組件:HomeView.vue

<template>
  <div class="home">
    <myChild ref="child" />
    <myChild2 ref="child2" />
    <button @click="add">點(diǎn)擊</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>

結(jié)果

從下圖結(jié)果可以看出,可以通過(guò)ref訪(fǎng)問(wèn)myChild2組件,但是無(wú)法訪(fǎng)問(wèn)myChild組件,

在這里插入圖片描述

原因

vue3項(xiàng)目使用<script setup>語(yǔ)法糖相比于使用setup()函數(shù)會(huì)更加方便簡(jiǎn)潔,但前者會(huì)將組件私有化,也就是說(shuō)使用<script setup>的組件中的數(shù)據(jù)和事件無(wú)法被外部訪(fǎng)問(wèn),此時(shí)父組件就無(wú)法通過(guò)ref去訪(fǎng)問(wèn)該子組件。

除非主動(dòng)對(duì)外暴露 setup 中的數(shù)據(jù)和方法,使用 defineExpose API,此時(shí)你可以向外暴露任何你允許外部訪(fǎng)問(wèn)的

<!-- myChild -->

<script setup>
import { ref, defineExpose } from 'vue'
const num = ref(0)
const insert = () => {
  num.value++
}
// 向外暴露 insert 事件
defineExpose({ insert, a: 1, b: 2 })

</script>

在這里插入圖片描述

到此這篇關(guān)于vue3 ref獲取不到子組件的解決方法的文章就介紹到這了,更多相關(guān)vue3 ref獲取不到子組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論