navigo
navigo copied to clipboard
The data-navigo attribute does not work in the Lit component.
Clicking on the Home and About links triggers internal navigation within the SPA. However, clicking on the Contact link causes the browser to reload the page.
<!DOCTYPE html>
<html>
<head>
<title>Lit + Navigo SPA</title>
<script type="module">
import { LitElement, html, css } from 'https://gcore.jsdelivr.net/gh/lit/dist@2/core/lit-core.min.js';
import Navigo from 'https://cdn.skypack.dev/navigo';
class AppRoot extends LitElement {
static styles = css`
:host {
display: block;
}
nav {
background: #f8f9fa;
padding: 1rem;
}
nav a {
margin-right: 1rem;
text-decoration: none;
color: #007bff;
}
nav a:hover {
text-decoration: underline;
}
main {
padding: 1rem;
}
`;
constructor() {
super();
this.currentPage = html`<home-page></home-page>`;
this.router = new Navigo('/');
}
connectedCallback() {
super.connectedCallback();
this.router
.on('/', () => {
this.currentPage = html`<div>Home</div>`;
this.requestUpdate();
})
.on('/about', () => {
this.currentPage = html`<div>About</div>`;
this.requestUpdate();
})
.on('/contact', () => {
this.currentPage = html`<div>Contact</div>`;
this.requestUpdate();
})
.resolve();
}
render() {
return html`
<nav>
<a href="/" @click=${(event) => { event.preventDefault(); this.router.navigate('/'); }}>Home</a>
<a href="/about" @click=${(event) => { event.preventDefault(); this.router.navigate('/about'); }}>About</a>
<a href="/contact" data-navigo>Contact</a>
</nav>
<main>
${this.currentPage}
</main>
`;
}
}
customElements.define('app-root', AppRoot);
window.addEventListener('load', () => {
console.log('Page was reloaded');
});
</script>
</head>
<body>
<app-root></app-root>
</body>
</html>