我怎样才能赶上路线变更?



我用'tinro'

我可以用'beforeunload'方法捕捉窗口中的变化。(关机,手动更改url,关闭窗口或浏览器)。但是当我想通过点击我用"tinro"创建的链接来更改页面时,我无法捕获"beforeunload"。如何解决这个问题?

如果在项目中的表单页面中有更改,如果要更改路由或者要更改url路径,我需要在页面中捕获此。

每次路由改变时,onRouteChange将被调用:

添加到layout .svelte:

<script lang="ts">
import { navigating } from '$app/stores';
$: if($navigating) onRouteChange();
</script>

根据包文档,你可以使用路由器订阅方法。router对象是一个有效的Svelte存储,所以你可以订阅以获取不断变化的导航数据。

import { router } from 'tinro';
const currentpath = String($router.url);
// subscribe to the route changes
router.subscribe((nextRoute) => {
// if the user is navigating away from the current page
if (nextRoute.url !== currentpath) {
try {
// if the form was modified show confirmation dialog
if (JSON.stringify(form) !== JSON.stringify(resetForm)) {
// if the user clicked cancel stay in the same page
if(window.confirm("Are you sure you want to exit without saving?") == false)
throw new Error();
// else (user clicked ok) continue navigation to the next route
}
} catch (error) {
// return to current page. In other words stay in the same page
router.goto(currentpath);
}
}
});

最新更新