vue的两种路由方式

166 阅读1分钟

以下表格总结了这两种路由方式的实现方式、特性和适用场景。

路由模式实现方式URL 表现形式优点缺点适用场景
Hash 模式使用 URL 的 hash (#) 部分实现,通过 window.location.hash 监听 URL 变化。http://example.com/#/path兼容性好,不需要服务器配置。URL 中有 #,不够美观。兼容性要求高、无需服务器配置的场景。
History 模式使用 HTML5 的 history.pushState()history.replaceState() 实现,依赖浏览器 History APIhttp://example.com/pathURL 结构清晰,符合标准 URL 规范,利于 SEO。需要服务器支持,在刷新时需正确路由配置。SEO 友好、服务器支持 HTML5 History 的场景。

详细实现方式

Hash 模式

  1. 在 Vue Router 配置中指定 mode: 'hash'

    import { createRouter, createWebHashHistory } from 'vue-router';
    
    const router = createRouter({
      history: createWebHashHistory(),
      routes: [
        { path: '/', component: Home },
        { path: '/about', component: About },
      ],
    });
    
  2. Hash 模式通过 URL # 后面的部分识别路由路径,页面不会重新加载。

History 模式

  1. 在 Vue Router 配置中指定 mode: 'history'

    import { createRouter, createWebHistory } from 'vue-router';
    
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        { path: '/', component: Home },
        { path: '/about', component: About },
      ],
    });
    
  2. History 模式需要服务器支持 URL 重写,否则页面刷新时会产生 404 错误。一般的配置示例如下:

    • Nginx 配置示例:
      location / {
        try_files $uri $uri/ /index.html;
      }
      
    • Apache 配置示例(.htaccess 文件):
      <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
      </IfModule>
      

总结

  • Hash 模式 适用于快速开发、无需复杂服务器配置的项目。
  • History 模式 更适合需要 SEO 支持、对 URL 美观度要求较高的项目。