【问题标题】:Route as modal in Sapper在 Sapper 中作为模态路由
【发布时间】:2020-07-25 20:18:00
【问题描述】:

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

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

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

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

如何在 Sapper 中实现它?

感谢您的宝贵时间。

【问题讨论】:

  • 这个问题你解决了吗?
  • 这有什么更新吗?努力实现同样的目标。
  • 我真的怀疑如果不改变核心,这是否可能——所以如果你真的想要它,你应该考虑在 Github->sapper 中打开一个问题,为它建立社区支持,并为它贡献一个 PR它。我说,b/c 我猜你需要一种在没有 _layout.svelte 的情况下呈现/获取页面的方法

标签: routing svelte sapper


【解决方案1】:

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

<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 函数并将生成的道具作为本地道具注入。然后我检查是否设置了任何 props,然后根据它注入自定义 HTML。

“真实页面”只是一个包含&lt;Post title={post.title} html={post.html} /&gt;的工兵组件

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2020-02-21
    • 2020-02-18
    • 1970-01-01
    • 2021-01-18
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多