Chciałem stworzyć jakiś w miarę ciekawy navbar z wskaźnikiem aktualnie otwartej karty(chodzi o ten pasek pod linkiem), aktualnie wygląda to tak, jak niżej:
Problem polega na tym, że przy pierwszym załadowaniu strony wskaźnik się nie aktualizuje,
kod komponentu Navbar:
<template>
<nav>
<RouterLink to="/"><img :src="logo" alt="Logo" /></RouterLink>
<ul class="links" @mouseleave="fixIndicator" @resize="fixIndicator">
<li @mouseenter="moveIndicator" :class="{ active: route.name == 'home' }">
<RouterLink to="/">Home</RouterLink>
</li>
<li @mouseenter="moveIndicator" :class="{ active: route.name == 'about' }">
<RouterLink to="/about">About</RouterLink>
</li>
<li @mouseenter="moveIndicator" :class="{ active: route.name == 'team' }">
<RouterLink to="/team">Our team</RouterLink>
</li>
<li @mouseenter="moveIndicator" :class="{ active: route.name == 'demo' }">
<RouterLink to="/demo">Demo</RouterLink>
</li>
<span id="indicator"></span>
</ul>
</nav>
</template>
<script>
import { animate } from "motion";
import { RouterLink, useRoute } from "vue-router";
import logo from "../assets/img/logo.png";
export default {
name: "Navbar",
data() {
return {
logo: logo,
};
},
methods: {
moveIndicator(e) {
const node = e.target;
const nodeLeft = node.offsetLeft;
const nodeWidth = node.offsetWidth;
animate("#indicator", { width: `${nodeWidth}px`, left: `${nodeLeft}px` }, { duration: 0.2, easing: "ease-in-out" });
},
fixIndicator() {
const node = document.querySelector("nav .links li.active");
if (node == null) {
console.error("Active link not found.");
return;
}
const nodeLeft = node.offsetLeft;
const nodeWidth = node.offsetWidth;
animate("#indicator", { width: `${nodeWidth}px`, left: `${nodeLeft}px` }, { duration: 0.2, easing: "ease-in-out" });
},
},
computed: { route: () => useRoute() },
};
</script>
Próbowałem wywoływania metody fixIterator
podczas onMount
, ale wyrzucało błąd(node byl undefined).
Pewnie jest do tego jakiś event, ale nie mam pojęcia jaki.
Z góry dzięki.