首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >路由作为Sapper中的模式

路由作为Sapper中的模式
EN

Stack Overflow用户
提问于 2020-04-13 17:39:25
回答 1查看 411关注 0票数 3

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

它所做的是,当点击一个链接时,新页面以模式显示,而不是替换当前页面,并且URL被更新,反映当前模式页面。它在几个社交网络中得到了应用,比如instagram。

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

代码语言:javascript
复制
<Link href={`/?postId=${id}`} as={`/post/${id}`}>

如何在Sapper中实现它?

耽误您时间,实在对不起。

EN

回答 1

Stack Overflow用户

发布于 2020-09-10 22:43:39

我设法做到了这一点:

代码语言:javascript
复制
<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}

我不得不手动处理弹出状态事件(这样back按钮仍然有效)。然后,我使用了sapper prefetch函数,并将生成的道具作为本地道具注入。然后我检查是否设置了任何道具,然后根据它注入自定义HTML。

真正的页面只是一个包含<Post title={post.title} html={post.html} />的简单组件

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61185073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档