gpt4 book ai didi

routing - 在 Sapper 中作为模态路由

转载 作者:行者123 更新时间:2023-12-04 04:13:42 25 4
gpt4 key购买 nike

我正在尝试在 Sapper 中实现 next.js 中所做的事情名为 with-route-as-modal 的示例.

它的作用是,当单击链接时,新页面以模态显示而不是替换当前页面,并且 URL 会更新,以反射(reflect)当前模态页面。它在多个社交网络中实现,例如 instagram。

next.js例如,它是通过使用动态 href 来完成的,如下所示:

<Link href={`/?postId=${id}`} as={`/post/${id}`}>

如何在 Sapper 中实现它?

谢谢你的时间。

最佳答案

我设法以这种方式做到了:

<script>
import { prefetch } from '@sapper/app'
import { onMount, onDestroy } from 'svelte'
import Post from '../components/Post.svelte'

let props

onMount(() => {
window.onpopstate = function (event) {
if (document.location.pathname === '/about') {
props = null
} else {
const regex = /\/blog\/([\w-]+)/
if (regex.test(document.location.pathname)) {
handlePrefetch(document.location.pathname)
}
}
}

return () => {
window.onpopstate = null
}
})

function handleClick(event) {
event.preventDefault()
const clickedHref = event.currentTarget.href
if (clickedHref === location.href) return

const pathname = clickedHref.replace(location.origin, '').substring(1)
history.pushState(null, '', pathname)
handlePrefetch(pathname)
}

async function handlePrefetch(url) {
const res = await prefetch(url)
const { branch } = res
props = branch[1].props.post
}

function handleClose() {
history.pushState(null, '', 'about')
props = null
}
</script>

<svelte:head>
<title>About</title>
</svelte:head>

<h1>About this site</h1>

<p>This is the 'about' page. There's not much here.</p>

<a href="/blog/what-is-sapper" on:click="{handleClick}">lien ici</a>

{#if props}
<Post title="{props.title}" html="{props.html}"></Post>
<button on:click="{handleClose}"></button>
{/if}

我必须手动处理弹出状态事件(这样后退按钮仍然有效)。然后我用工兵 prefetch函数并将生成的 Prop 作为本地 Prop 注入(inject)。然后我检查是否设置了任何 Prop ,然后根据它注入(inject)自定义 HTML。
“真实页面”只是一个包含 <Post title={post.title} html={post.html} /> 的工兵组件。

关于routing - 在 Sapper 中作为模态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61185073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com