Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

Router.svelte 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <main>
  2. <svelte:component this={currentElement} {...currentProps} />
  3. </main>
  4. <script>
  5. export let routes;
  6. let routeMap = new Map();
  7. for (let route of routes) {
  8. let [descriptor, el] = route;
  9. let parts = descriptor.split("/:");
  10. let props = parts.slice(1);
  11. let base = parts[0] + "@" + props.length;
  12. routeMap.set(base, {props, el});
  13. }
  14. let currentElement = null;
  15. let currentProps = null;
  16. function route() {
  17. let path = location.hash.substr(1);
  18. if (path[0] != "/") {
  19. console.error("Illegal path:", path);
  20. path = "/";
  21. }
  22. let parts = path.split("/").filter(el => el != "");
  23. let base = "/" + parts.join("/") + "@0";
  24. let propVals = [];
  25. let route = routeMap.get(base);
  26. // Check if we match anything, removing one path component every iteration
  27. while (route == null && parts.length > 0) {
  28. propVals.push(parts.pop());
  29. base = "/" + parts.join("/") + "@" + propVals.length;
  30. route = routeMap.get(base);
  31. }
  32. if (route == null) {
  33. console.warn("No route matches", path);
  34. route = routeMap.get("/@0");
  35. }
  36. let props = {};
  37. for (let propName of route.props) {
  38. props[propName] = propVals.pop();
  39. }
  40. currentElement = route.el;
  41. currentProps = props;
  42. }
  43. route();
  44. window.addEventListener("hashchange", route);
  45. </script>