[英]Vue3 composition API - accessing child ref
我正在嘗試使用 Vue3 組合 API 訪問子組件中的 ref,但我不確定該怎么做。 我想向mainContentRef
添加一個滾動事件,這樣我就可以執行獲取請求以在父組件中獲取更多數據,但我似乎無法訪問父組件中的 ref 以向其添加事件偵聽器
這是我的代碼(由於本示例不需要,因此刪除了一些部分):
<!-- MAIN COMPONENT -->
<template>
<PageWrap>
<template v-slot:content>
<MainContent>
<template v-slot:content />
</MainContent>
</template>
</PageWrap>
</template>
<script setup>
//access mainContentRef here because this is where the fetch request will be
</script>
<!-- MAIN CONTENT COMPONENT -->
<template>
<div id="main-content" ref='mainContentRef'>
<slot name='content'></slot>
</div>
</template>
<script setup>
import { defineProps, ref } from 'vue';
const mainContentRef = ref(0);
</script>
您可以利用 vue 的defineExpose
方法,然后為您的MainContent
組件添加一個ref
並通過它訪問它。
<!-- MAIN COMPONENT -->
<template>
<PageWrap>
<template v-slot:content>
<MainContent ref="mainContentComponent">
<template v-slot:content />
</MainContent>
</template>
</PageWrap>
</template>
<script setup>
const mainContentComponent = ref()
// Now you can do:
mainContentComponent.value.mainContentRef.value
</script>
<!-- MAIN CONTENT COMPONENT -->
<template>
<div id="main-content" ref="mainContentRef">
<slot name='content'></slot>
</div>
</template>
<script setup>
import { defineProps, ref } from 'vue'
const mainContentRef = ref(0)
defineExpose({
mainContentRef
})
</script>
另見: https ://vuejs.org/guide/essentials/template-refs.html#ref-on-component
如果您有任何問題或它不起作用,請告訴我,很樂意為您提供幫助!
你可以試試:
<!-- MAIN CONTENT COMPONENT -->
<template>
<div id="main-content" ref='mainContentRef'>
<slot name='content'></slot>
</div>
</template>
<script setup>
import { defineProps, ref } from 'vue';
const mainContentRef = ref(null);
// Now you can do:
mainContentRef.value.children[0]
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.