我有一个页面,该页面带有带有“季度”链接的导航栏。在“季度”链接下,当用户在/quarters
路线上时,将显示一个季度列表,例如2019Q2等。URL为/quarters/2019q2
。
我想制作一个显示超级链接的组件,如果当前URL与链接的href匹配,则该超级链接将具有selected
类。这是我能得到的最接近的东西:
<script>
import { afterUpdate } from 'svelte';
export let segment;
export let text = 'text here';
export let link;
let isCurrentPath = false;
console.log(segment, link, text);
afterUpdate(() => {
if (window.location.pathname.includes(link)) {
isCurrentPath = true;
debugger;
}
console.log('HL afterUpdate ', window.location);
});
</script>
<style>
/* omitted */
</style>
<a class:selected={segment && isCurrentPath} href={link}>{text}</a>
对于第一次加载来说效果很好,但是当用户导航到其他数据页面时,选择不会更新。如何获得一些仅在客户端运行的代码?如果我访问window
之外的afterUpdate
对象,则会从服务器端代码中得到null ref错误。
ETA:也尝试过此方法:
let isCurrentPath = false;
let path = typeof window === 'undefined' ? '' : window.location.pathname;
$: if (path) isCurrentPath = window.location.pathname.includes(link);
当用户单击数据链接之一时,该代码不会触发。也尝试过onMount
,但没有任何积极的结果。
答案 0 :(得分:1)
对于使用 SvelteKit 的人,给出的答案仍然适用。查看页面存储的文档:https://kit.svelte.dev/docs#loading-input-page
答案 1 :(得分:0)
而不是使用> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4
,我相信您应该考虑使用afterUpdate
编写一些东西,并使用反应性语句https://svelte.dev/examples#reactive-statements让您无论何时都想重新计算onMount
位置更改。
答案 2 :(得分:0)
技巧是根据页面存储中的值创建反应式语句。
<!--
This is used to have a link on the page that will show highlighted if the url meets the criteria.
You might want to adjust the logic on line 19.
usage:
<HighlightedLink bind:segment highlight="faq" rel="prefetch" link="/faq" text="FAQ" />
-->
<script>
import { stores } from '@sapper/app';
const { page } = stores();
export let highlight;
export let segment;
export let text = 'text here';
export let link;
export let target;
let highlightPath = false;
$: highlightPath =
$page.path && highlight && ($page.path.includes(highlight) || $page.path.includes(link));
</script>
<style>
.selected {
position: relative;
display: inline-block;
}
.selected::after {
position: absolute;
content: '';
width: calc(100% - 1em);
height: 2px;
background-color: rgb(255, 62, 0);
display: block;
bottom: -1px;
}
a {
padding-left: 10px;
}
</style>
<a class:selected={highlightPath} href={link}>{text}</a>