在 Vue 3 和 TypeScript 的环境下,你可以通过组合式 API 的 onMounted 和 onUnmounted 生命周期钩子函数来监听页面滚动事件,并通过 ref 来获取子组件的引用,然后调用子组件的方法。以下是一个简单的示例:
<template>
<ChildComponent ref="child" />
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const child = ref<InstanceType<typeof ChildComponent>>();
const handleScroll = () => {
if (window.scrollY > 100) {
child.value?.setStyle(); // 调用子组件的 setStyle 方法
}
};
onMounted(() => {
window.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
});
</script>在这个例子中,我们首先导入了子组件 ChildComponent,并使用 ref 创建了一个引用 child。在 onMounted 钩子中,我们添加了一个滚动事件监听器,它会在用户滚动页面时调用 handleScroll 函数。在 handleScroll 函数中,我们检查了页面的滚动位置,并且如果滚动超过了 100 像素,我们通过 child.value?.setStyle() 调用了子组件的 setStyle 方法。最后,在 onUnmounted 钩子中移除了滚动事件监听器,避免在组件卸载后发生内存泄露。
确保子组件 ChildComponent 有一个 setStyle 方法供你调用。如果子组件是由单文件组件定义的,那么它应该有一个导出的方法 setStyle。如果子组件是通过 script setup 定义的,那么你可以直接在子组件内部定义方法,并在父组件中通过 ref 调用。