在Sapper中作为模态路由

时间:2020-04-13 09:39:24

标签: routing svelte sapper

我正在尝试在Sapper中实现名为with-route-as-modalnext.js示例中完成的操作。

它的作用是,单击链接时,新页面以模式显示,而不是替换当前页面,并且URL更新,以反映当前模式页面。它在instagram等多个社交网络中实现。

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

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

如何在Sapper中实现它?

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

我设法做到了:

<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}

我必须手动处理弹出状态事件(以便后退按钮仍然有效)。然后,我使用了Sapper prefetch函数,并将生成的道具注入为本地道具。然后,我检查是否设置了任何道具,然后根据它插入自定义HTML。

“真实页面”只是一个包含<Post title={post.title} html={post.html} />

的工具组件