如何在 Composition API 中构建 IntersectionObserver?

Art*_*nov 5 javascript jetbrains-ide vue.js vuejs3 vue-composition-api

我正在尝试实现一个当视口移动到新部分时IntersectionOberver会改变的。url我找到了这个线程,现在试图让它工作vue 3 compositon api.

\n

我正在尝试在我的中实现该脚本index.vue文件中实现该脚本,该文件是所有其他 vue 组件的父级:

\n
<template>\n  <div class="container">\n    <navbar></navbar>\n    <social-media-bar></social-media-bar>\n    <main>\n      <home></home>\n      <news></news>\n      <vision></vision>\n      <event-section></event-section>\n      <artwork></artwork>\n      <about></about>\n      <donate></donate>\n      <contact></contact>\n      <partners></partners>\n    </main>\n    <footer-component></footer-component>\n  </div>\n</template>\n\n\n<script setup>\nimport ... // component imports\nimport {onMounted, reactive} from "vue";\nimport router from "../js/router";\n\nconst state = reactive({\n    sectionObserver: null\n})\n\nconst sectionObserveHandler = (entries) => {\n    for (const entry of entries) {\n        if (entry.isIntersecting) {\n            router.push({name: \'news\', hash: \'#news\'})\n        }\n    }\n}\n  \nconst observeSections = () => {\n    const options = {\n        rootMargin: \'0px 0px\',\n        threshold: 0\n    }\n    state.sectionObserver = new IntersectionObserver(sectionObserveHandler, options)\n    const sections = document.querySelectorAll(\'.section\')\n    sections.forEach(section =>{\n        state.sectionObserver.observe(section)\n    })\n}\n\nonMounted(() => {\n    observeSections()\n})\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

基本上,我现在想要的是将视口滚动到下一个时更改url.../#newssection

\n

当我启动网络应用程序时,它可以正常工作,没有错误消息,但没有url change向下滚动到各个部分时不会出现任何错误消息。

\n

我究竟做错了什么?

\n

我注意到 Phpstorm 在这一行告诉我:

\n
state.sectionObserver = new IntersectionObserver(sectionObserveHandler, options)\n
Run Code Online (Sandbox Code Playgroud)\n

那:

\n
Assigned expression type IntersectionObserver is not assignable to type UnwrapRef<null> ... \xc2\xa0\xc2\xa0Type IntersectionObserver is not assignable to type null extends ShallowRef<infer V> ? V : (null extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<null>) \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type IntersectionObserver is not assignable to type null extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<null>\n
Run Code Online (Sandbox Code Playgroud)\n

我已经state.sectionObserver改为string,integerarray错误仍然存​​在。不确定这是否与此工作相关,因为浏览器似乎忽略了它。

\n

Art*_*nov 1

在 Kevin Powell 的这个很棒的教程的帮助下找到了答案。

必须将其放入我的index.vue标签中script setup

onMounted(() => {
    const sections = document.querySelectorAll('section')
    const options = {
        threshold: 0.5
    }
    const observer = new IntersectionObserver(function(entries, observer) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                console.log(entry.target)
            }
        })
    }, options)
    sections.forEach(section => {
        observer.observe(section)
    })
})
Run Code Online (Sandbox Code Playgroud)