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

Vue3中使用setup通過ref獲取子組件的屬性

 更新時(shí)間:2022年07月28日 09:34:40   作者:小火車況且況且  
這篇文章主要介紹了Vue3中使用setup通過ref獲取子組件的屬性,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

setup通過ref獲取子組件的屬性

主要依賴defineExpose

子組件通過 defineExpose將數(shù)據(jù)拋出

<template>
? <div class="test-com">testCom</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const testText = ref('我是子組件的數(shù)據(jù)')
defineExpose({
? text: testText
})
</script>

父組件通過給子組件綁定ref 然后結(jié)合nextTick回調(diào)函數(shù)獲取子組件的數(shù)據(jù)

<template>
? <div>
? ? <TestCom ref="getTestComRef" />
? ? {{ showText }}
? </div>
</template>
<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import TestCom from './components/TestCom.vue'
const getTestComRef = ref<{
? text: string
}>()
const showText = ref()
nextTick(() => {
? showText.value = getTestComRef.value?.text
})
</script>

效果圖

調(diào)用子組件的屬性和方法

今天在寫 vue3 項(xiàng)目時(shí),需要在父組件里面調(diào)用子組件的方法,但是打印出來(lái)卻是這個(gè)樣子:

發(fā)現(xiàn)打印出來(lái)的數(shù)據(jù)啥都沒有,難道是代碼問題?

上代碼:

父組件代碼

<template>
? <son ref="sonRef"></son>
</template>
<script setup>
import { onMounted, ref } from "vue";
import Son from "./view/son.vue";
const sonRef = ref(null);
onMounted(() => {
? console.log(sonRef.value);
});
</script>

son 組件代碼

<template>
? <div>子組件</div>
</template>
<script setup>
const a = "555";
const fn = () => {
? console.log("執(zhí)行了fn");
};
</script>

通過翻閱 vue 文檔發(fā)現(xiàn)文檔中寫著一個(gè)叫 defineExpose 的 api,是這樣介紹的:

使用 <script setup> 的組件是默認(rèn)關(guān)閉的,也即通過模板 ref 或者 $parent 鏈獲取到的組件的公開實(shí)例,不會(huì)暴露任何在 <script setup> 中聲明的綁定。

大致意思就是:使用 script setup 語(yǔ)法糖的組件,不會(huì)往外暴露任何在該語(yǔ)法糖中聲明的變量,需要使用defineExpose 語(yǔ)法來(lái)將你想暴露出去的變量和方法暴露出去

son 組件代碼修改后:

<template>
? <div>子組件</div>
</template>
<script setup>
const a = "555";
const fn = () => {
? console.log("執(zhí)行了fn");
};
defineExpose({
? a,
? fn,
});
</script>

然后就可以在控制臺(tái)看到我們?cè)诳刂婆_(tái)打印出了子組件上變量和方法,然后就可以進(jìn)行調(diào)用了

over,問題解決!

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論