vue3路由模式为history,打包后页面空白的处理方式

4/4/2022 vue3historynginx

# 场景

vue-router 的 hash 模式时,url始终待着'#',如'http://localhost:8080/#/index.html'。 如果要去掉'#'号,那么就需要把 vue-router 的 hash 模式改为 history(html5)模式。

# vue3

const router = createRouter({
  //hash 模式  
  // history: createWebHashHistory(),
  //html5 模式
  history: createWebHistory("/"),
  routes
})
1
2
3
4
5
6
7
8
9

# 问题

hash 模式打包后的 dist 文件夹中可以直接打开 index.html 看到页面。 但是 history 模式打包后,打开 /dist/index.html 时会出现页面空白现象。

# 解决方案

vue 官网的模式说明 (opens new window) vue-router 的 createWebHistory (opens new window) 官网上解释了出现这种问题的原因,我们需要进行如下的几步配置。

# 1. 配置 vue.config.js 中的 publicPath

# vue.config.js

module.exports = {
  //根目录
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
};
1
2
3
4
5
6

# 2.配置 vue-router

const router = createRouter({
  //根目录
  history: createWebHistory("/"),
  routes
})
1
2
3
4
5

# 3.配置 nginx 的 server

location / {
    root   /opt/app/fontend;
    index index.html index.htm;
    try_files  $uri $uri/ /index.html;
}
1
2
3
4
5

把打包后生成的 css、js、html 等文件放入服务器中的/opt/app/fontend目录下,访问对应 ip:端口 即可看到页面。

上次更新: 2024/09/10 17:37:12
最近更新
01
跨域的几种常见解决方案
04-03
02
react教程
03-01
03
前端抓包神器whistle
09-01