Skip to content

Commit 1f3e1ff

Browse files
committed
Added RouterOutlet for displaying the correct view depending on the current route
1 parent 77596db commit 1f3e1ff

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1+
import { RouterLink } from './routing/router-component.js';
2+
13
export { createApp } from './app';
24
export { DOM_TYPES, hString, hElement, hFragment, hSlot } from './h';
35
export { defineComponent } from './components/component';
46
export { nextTick } from './next-tick.js'
7+
export { RouterLink, RouterOutlet } from './routing/router-component.js'
8+
export { HashRouter } from './routing/hash-router.js'
9+

src/routing/router-component.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { defineComponent } from '../components/component'
22
import { hElement, hSlot } from '../h'
33

4+
// <RouterLink to="/profil">profil</RouterLink>
45
export const RouterLink = defineComponent({
56
render() {
67
const { to } = this.props
@@ -16,3 +17,37 @@ export const RouterLink = defineComponent({
1617
[hSlot()])
1718
}
1819
})
20+
21+
export const RouterOutlet = defineComponent({
22+
state() {
23+
return {
24+
matchedRoute: null,
25+
subscription: null,
26+
}
27+
},
28+
29+
onMounted() {
30+
const subscription = this.appContext.router.subscribe(({ to }) => {
31+
this.handleRouteChange(to);
32+
})
33+
34+
this.updateState({ subscription });
35+
},
36+
37+
onUnmounted() {
38+
const { subscription } = this.state;
39+
this.appContext.router.unsubscribe(subscription);
40+
},
41+
42+
handleRouteChange(matchedRoute) {
43+
this.updateState({ matchedRoute });
44+
},
45+
46+
render() {
47+
const { matchedRoute } = this.state;
48+
49+
return hElement('div', { id: 'router-outlet' }, [
50+
matchedRoute ? hElement(matchedRoute.component) : null
51+
])
52+
},
53+
})

0 commit comments

Comments
 (0)