File tree Expand file tree Collapse file tree 3 files changed +76
-0
lines changed
packages/test-vanilla/src/history-router Expand file tree Collapse file tree 3 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html >
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < meta http-equiv ="X-UA-Compatible " content ="IE=edge ">
6+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
7+ < title > Document</ title >
8+ </ head >
9+ < body >
10+ < div >
11+ < button onclick ="router.navigate('/') "> home</ button >
12+ < button onclick ="router.navigate('/app') "> app</ button >
13+ </ div >
14+ < div id ="root "> </ div >
15+ </ body >
16+ < script src ="./router.js "> </ script >
17+ < script >
18+ const router = new Router ( )
19+ router . add ( '/' , ( ) => {
20+ return `<p>home</p>`
21+ } )
22+ router . add ( '/app' , ( ) => {
23+ return `<p>app</p>`
24+ } )
25+ router . listen ( ( html ) => {
26+ const root = document . querySelector ( '#root' )
27+ root . innerHTML = html
28+ } )
29+ </ script >
30+ </ html >
Original file line number Diff line number Diff line change 1+ # history router
2+
3+ 相关的api
4+ - history.forward
5+ - history.back
6+ - history.go(n)
7+ - history.pushState(data, title, url)
8+ - history.replaceState(data, title, url)
9+ - history.state
10+ - popstate
Original file line number Diff line number Diff line change 1+ class Router {
2+ routers = [ ]
3+ add ( path , render ) {
4+ this . routers . push ( {
5+ path,
6+ render,
7+ } )
8+ }
9+ listen ( callback ) {
10+ this . callback = callback
11+ window . addEventListener ( 'popstate' , ( ) => {
12+ this . handle ( )
13+ } )
14+ this . handle ( )
15+ }
16+ handle ( ) {
17+ const path = ( location . pathname || '/' )
18+ for ( const router of this . routers ) {
19+ if ( router . path === path ) {
20+ this . callback ( router . render ( ) )
21+ return
22+ }
23+ }
24+ }
25+ navigate ( path , options = {
26+ state : undefined ,
27+ replace : false
28+ } ) {
29+ if ( options . replace ) {
30+ history . replaceState ( options . state , '' , path )
31+ } else {
32+ history . pushState ( options . state , '' , path )
33+ }
34+ this . handle ( )
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments