Vue-Router 的 hash 和 history 模式配置

vue的路由有两种模式,默认为 hash模式,还有一种为 history 模式,这两种模式显式的最大区别是,浏览器地址栏 hash 模式在末尾带有 # ,而 history 模式不带 #。下面介绍两种模式的配置(在vue-cli3.x下创建的项目)。

有三个地方需要配置,一个是 vue.config.js,一个是 router/index.js,一个是 nginx 线上部署配置。

hash 模式

  • vue.config.js 配置配置 publicPath 为 “./”
  • router/index.js 配置mode 修改为 “history”
  • nginx 线上部署
location /xxx{
    root  E:/nginxVueApps/;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
}
# 注:xxx为打包后的项目名称
  • 访问

localhost:8080/xxx

最终浏览器地址栏的 url 为 localhost:8080/xxx/#/,也就是 hash 模式会带有 #

history 模式

  • vue.config.js 配置配置 publicPath 为 “/xxx”
  • router/index.js 配置mode 修改为 “history”
  • nginx 线上部署
 location /xxx{
     root E:/nginxVueApps/;
     index index.html index.htm;
     try_files $uri $uri/ /index.html;
 }
 # 注:xxx为打包后的项目名称,在 vue.config.js 的配置中
 # 要将 publicPath 配置为 "/打包后的项目名称",否则打包后访问页面为空白
  • 访问

localhost:8080/xxx最终浏览器地址栏的 url 为 localhost:8080/xxx,也就是 history 模式不会带有还有一点。

注意

需要注意的是 history 模式如果直接在浏览器里面输入路由里的访问地址,页面还是会空白的,需要使用 router 的跳转,如在理由里面配置了一个页面

  {
    // operation
    path: '/o',
    name: 'Operation',
    component: () => import('../components/Operation')
  },

上线部署后,如果直接在浏览器里面输入 localhost:8080/xxx/o,这样的页面是空白的,需要使用跳转的方法,如

this.$router.push(
    {
          path: '/o',
    })

这样才能正常访问

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值