Bry*_*n88 12 javascript vuejs3 vue-composition-api
我正在尝试使用 Vue3 组合 API 访问子组件中的引用,但我不确定如何执行此操作。我想向其中添加一个滚动事件,mainContentRef
以便我可以执行获取请求以获取父组件中的更多数据,但我似乎无法访问父组件中的引用以向其添加事件侦听器
这是我的代码(由于本示例不需要某些部分而被删除):
<!-- 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>
Run Code Online (Sandbox Code Playgroud)
zlo*_*owe 20
您可以利用 vue 的defineExpose
方法,然后ref
为您的MainContent
组件添加 a 并通过它访问它。
<!-- 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 { ref } from 'vue'
const mainContentRef = ref(0)
defineExpose({
mainContentRef
})
</script>
Run Code Online (Sandbox Code Playgroud)
另请参阅: https: //vuejs.org/guide/essentials/template-refs.html#ref-on-component
如果您有任何疑问或不起作用,请告诉我,很乐意为您提供帮助!