原生js 模拟Vue路由切换

    实现原理:进啊听hashchange,hash改变的时候,根据当前的hash匹配相应的html内容,然后用innerHTMl把html内容放进router-view里面

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body>
    9. <div class="container">
    10. <ul>
    11. <li><a href="#/">主页</a></li>
    12. <li><a href="#b">B</a></li>
    13. <li><a href="#c">C</a></li>
    14. </ul>
    15. <div class="viewer">
    16. 这是主页的内容
    17. </div>
    18. </div>
    19. </body>
    20. </html>
    21. <style>
    22. body,
    23. html {
    24. width: 100%;
    25. padding: 0;
    26. margin: 0;
    27. height: 100%;
    28. }
    29. .container {
    30. justify-content: center;
    31. align-items: center;
    32. font-size: 60px;
    33. display: flex;
    34. height: 100%;
    35. width: 100%;
    36. }
    37. .viewer {
    38. width: 50%;
    39. height: 20%;
    40. border: 2px solid red;
    41. margin-left: 30px;
    42. }
    43. </style>
    44. <script>
    45. class Router {
    46. constructor() {
    47. this.routes = new Map()
    48. this.currentUrl = ''
    49. this.refresh = this.refresh.bind(this)
    50. window.addEventListener('load', this.refresh, false)
    51. window.addEventListener('hashchange', this.refresh, false)
    52. }
    53. route(path, callback) {
    54. this.routes.set(path, callback)
    55. }
    56. refresh() {
    57. this.currentUrl = location.hash.slice(1) || '/'
    58. console.log(this.currentUrl)
    59. this.routes.get(this.currentUrl)()
    60. }
    61. }
    62. const routes = new Router()
    63. let viewer = document.querySelector('.viewer')
    64. routes.route('/', function () {
    65. viewer.innerHTML = '这是主页面'
    66. })
    67. routes.route('b', function () {
    68. console.log(1)
    69. viewer.innerHTML = '这是B页面'
    70. })
    71. routes.route('c', function () {
    72. viewer.innerHTML = '这是C页面'
    73. })
    74. console.log(routes.routes)
    75. </script>