vue-router 去掉#

时间:2023-03-08 22:07:29
vue-router 去掉#

  vue-router默认的路由模式是hash,我们要去掉url中的#需要将路由模式切换为history

const router = new VueRouter({
mode: 'history',
...
})

  这样子,url中的#就可以去掉了,在开发环境下不会出问题,部署上线后点击正常,但是...你一旦手动点击浏览器的刷新按钮,页面显示nginx的404页面。

  怎么解决呢?在vue-router官网有说明:这种模式还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。

  所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。我们线上的服务器用的是nginx,需要改为下面的配置:

# 项目部署在服务器/test目录下(访问地址:http://www.a.com/test)
location ^~/test {
     alias   D:/project/card-web/code/dist/;
try_files $uri $uri/ @card;
access_log logs/card_web.access.log ;
error_log logs/card_web.error.log ;
} location @card {
rewrite ^/(test)/(.+)$ /$/index.html last;
}

# 项目部署在服务器/下
(访问地址:http://www.a.com)
 location / {
root D:/project/card-web/code/dist/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}

  这样子,无论你怎么刷新页面都不会报404了。。。贼开心。。。

  然而,点进去一个二级路由发现,页面中的图片全都没有加载成功。。。vue-router官网有这么一句话:要注意,以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径。

  我页面中是这么写的:

<img :src="`./static/image/real-time-monitoring/online-line.png`"
alt="" class="line-img line-rotation">

  f12后发现,浏览器的请求路径是:

Request URL: http://localhost:8080/cardapp/card/static/image/real-time-monitoring/online-line.png

  我的路由:

{
path: '/cardapp',
component: CardApp,
name: 'cardapp',
children:[
{ path: 'card', component: add}
]
}

  解决办法:

<img :src="`/static/image/real-time-monitoring/online-line.png`"
alt="" class="line-img line-rotation">

  原因:这图片处在嵌套路由下,这个嵌套路由以 / 开头,会被当做根路径,之前写的相对路径会拼接到这个嵌套路由下,所有会出现图片路径会加上当前路由了。