代码之家  ›  专栏  ›  技术社区  ›  Artur Müller Romanov

如何在Inertia.js中操作浏览器url?

  •  0
  • Artur Müller Romanov  · 技术社区  · 4 年前

    我一直在使用 IntersectionObserver 更新 url 的 SPA 而用户像这样向下滚动页面:

    const sections = document.querySelectorAll('section')
    const options = {
        threshold: 0.5
    }
    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                router.push('#' + entry.target.id)
            }
        })
    }, options)
    sections.forEach(section => {
        observer.observe(section)
    })
    

    但是我该怎么做 Inertia.js 因为它没有 router.push 方法我正在使用 Inertia 带有 Vue 3 前端。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Jedupont    4 年前

    从前端导航时,惯性似乎保留了哈希: https://github.com/inertiajs/inertia/pull/257

    然而,从服务器上看,情况似乎并非如此: https://github.com/inertiajs/inertia/issues/729#issuecomment-1017619220

    如果这对你来说不是问题,你能简单地访问同一个URL并添加哈希吗?

    const id = entry.target.id
    const urlWithFragment = `${url}#${id}`
    
    Inertia.visit(urlWithFragment)
    

    默认情况下,http方法为 get ,但您可以自定义它:

    Inertia.visit(urlWithFragment, {method: 'post'})
    

    如果您使用ziggy,您可以轻松恢复当前路线:

    const currentRoute = route().current()
    const url = route(currentRoute)
    
    const urlWithFragment = `${url}#${id}`