Suppose you’re building a Svelte application using Sapper, and you have a dynamic page route, for example /routes/[id].svelte
.
假设您正在使用Sapper构建Svelte应用程序,并且具有动态页面路由,例如/routes/[id].svelte
。
You want to get the dynamic part of the URL (the id
in this case), and you know you can get it in the preload()
function in the <script context="module">
part of the component:
您想要获取URL的动态部分(在这种情况下为id
),并且知道可以在组件的<script context="module">
部分的preload()
函数中获取它:
<script context="module">
export async function preload({ params }) {
const { id } = params
}
</script>
But the problem is that you need to use it outside of preload()
, to perform something else.
但是问题是您需要在preload()
之外使用它来执行其他操作。
The way to do so is to return it from preload
, and define it as a prop of the component, using the usual export *
syntax.
这样做的方法是从preload
返回它,并使用通常的export *
语法将其定义为组件的支持。
Here’s an example:
这是一个例子:
<script context="module">
export async function preload({ params }) {
const { id } = params
return { id }
}
</script>
<script>
export let id
if (typeof window !== 'undefined') {
alert(id)
}
</script>
翻译自: https://flaviocopes.com/sapper-access-url-param-outside-module/