art*_*.mu 6 routes svelte sapper
我正在尝试在 Sapper 中实现名为with-route-as-modal 的next.js
示例中所做的操作。
它的作用是,当单击链接时,新页面会显示在模式中,而不是替换当前页面,并且 URL 会更新,反映当前的模式页面。它在多个社交网络中实施,例如 Instagram。
在next.js
示例中,它是通过使用动态 href 来完成的,如下所示:
<Link href={`/?postId=${id}`} as={`/post/${id}`}>
Run Code Online (Sandbox Code Playgroud)
我如何在 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}
Run Code Online (Sandbox Code Playgroud)
我必须手动处理弹出状态事件(以便后退按钮仍然有效)。然后我使用 sapperprefetch
函数并将生成的 props 作为本地 props 注入。然后我检查是否设置了任何 props,然后根据它注入自定义 HTML。
“真实页面”只是一个 sapper 组件,其中包含<Post title={post.title} html={post.html} />
归档时间: |
|
查看次数: |
800 次 |
最近记录: |