亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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 項目時,需要在父組件里面調(diào)用子組件的方法,但是打印出來卻是這個樣子:

發(fā)現(xiàn)打印出來的數(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)文檔中寫著一個叫 defineExpose 的 api,是這樣介紹的:

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

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

son 組件代碼修改后:

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

然后就可以在控制臺看到我們在控制臺打印出了子組件上變量和方法,然后就可以進(jìn)行調(diào)用了

over,問題解決!

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

相關(guān)文章

最新評論