router.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {dEvent} from "./helper.js";
  2. export default class Router {
  3. constructor(settings) {
  4. this.routes = settings.routes;
  5. for (let i = 0; i < this.routes.length;i++) {
  6. if (!this.routes[i].element) {
  7. const elementName = "template-" +this.routes[i].component.name.toLowerCase();
  8. if (!customElements.get(elementName)) customElements.define(elementName, this.routes[i].component);
  9. this.routes[i].element = document.createElement(elementName);
  10. console.log("CREATE " + elementName);
  11. }
  12. }
  13. this.link = settings.link || "router-link";
  14. this.view = settings.view || "router-view";
  15. this.home = window.location.toString();
  16. customElements.define(this.link, RouterLink);
  17. customElements.define(this.view, RouterView);
  18. this.bindEvents();
  19. }
  20. bindEvents() {
  21. document.addEventListener("router-click", (e)=> {
  22. let route = this.routes.find(route=>route.path === e.detail);
  23. if (!route) return;
  24. window.history.pushState({},e.path,this.home+String(e.detail));
  25. let el = document.querySelector(this.view);
  26. dEvent("router-view", route.element, el);
  27. })
  28. }
  29. }
  30. class RouterView extends HTMLElement {
  31. connectedCallback() {
  32. this.bindEvents()
  33. }
  34. bindEvents() {
  35. this.addEventListener("router-view",(e) => {
  36. this.innerHTML ="";
  37. this.append(e.detail);
  38. })
  39. }
  40. }
  41. class RouterLink extends HTMLElement {
  42. constructor() {
  43. super();
  44. this.bindEvents()
  45. }
  46. bindEvents() {
  47. this.addEventListener("click",() => {
  48. dEvent("router-click", this.getAttribute("to"))
  49. })
  50. }
  51. }