【发布时间】:2022-01-13 10:57:22
【问题描述】:
我正在尝试实现一个IntersectionOberver,当视口移动到新部分时,它将更改url。我找到了This thread,现在正试图让它在vue 3 compositon api 中工作。
我正在尝试在我的 index.vue 文件中实现脚本,该文件是所有其他 vue 组件的父级:
<template>
<div class="container">
<navbar></navbar>
<social-media-bar></social-media-bar>
<main>
<home></home>
<news></news>
<vision></vision>
<event-section></event-section>
<artwork></artwork>
<about></about>
<donate></donate>
<contact></contact>
<partners></partners>
</main>
<footer-component></footer-component>
</div>
</template>
<script setup>
import ... // component imports
import {onMounted, reactive} from "vue";
import router from "../js/router";
const state = reactive({
sectionObserver: null
})
const sectionObserveHandler = (entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
router.push({name: 'news', hash: '#news'})
}
}
}
const observeSections = () => {
const options = {
rootMargin: '0px 0px',
threshold: 0
}
state.sectionObserver = new IntersectionObserver(sectionObserveHandler, options)
const sections = document.querySelectorAll('.section')
sections.forEach(section =>{
state.sectionObserver.observe(section)
})
}
onMounted(() => {
observeSections()
})
</script>
基本上,我现在想要的是在视口滚动到下一个section 时将url 更改为.../#news。
当我启动网络应用程序时,它没有错误消息,但在向下滚动到部分时不会出现url change。
我做错了什么?
我注意到 Phpstorm 在这一行告诉我:
state.sectionObserver = new IntersectionObserver(sectionObserveHandler, options)
那个:
Assigned expression type IntersectionObserver is not assignable to type UnwrapRef<null> ... Type IntersectionObserver is not assignable to type null extends ShallowRef<infer V> ? V : (null extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<null>) Type IntersectionObserver is not assignable to type null extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<null>
我已将state.sectionObserver 更改为string、integer 或array,但错误仍然存在。不确定这是否与使这项工作相关,因为浏览器似乎忽略了它。
【问题讨论】:
-
这个问题是 IDE 特有的,一般来说没有意义。出于某种原因,在 JS 项目中启用了 Typescript 检查。这可能特定于您的配置。确保项目中没有使用 TS,并且项目根目录中没有 tsconfig.json。可能特定于
script setup在IDE 中的处理方式,尝试将其更改为常规脚本。它可以通过在stateinit 上执行new IntersectionObserver来修复,因为实例本身不依赖于 mount -
@EstusFlask 如何在
state init上创建IntersectionObserver? -
可能是
sectionObserver: new IntersectionObserver(...)? -
@EstusFlask 但
IntersectionObserver需要在设置期间创建的sectionObserverHandler和options。 -
在哪里创建它们取决于您。 sectionObserverHandler 和 options 中没有任何内容决定它们应该在 onMounted 中创建
标签: javascript vue.js vuejs3 jetbrains-ide vue-composition-api