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

场景

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
})

问题

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

解决方案

vue 官网的说明
官网上解释了出现这种问题的原因,我们需要进行如下的几步配置。

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

# vue.config.js

module.exports = {
    
    
  //根目录
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
};

2.配置 vue-router

const router = createRouter({
    
    
  //根目录
  history: createWebHistory("/"),
  routes
})

3.配置 nginx 的 server

location / {
    root   /opt/app/fontend;
    index index.html index.htm;
    try_files  $uri $uri/ /index.html;
}

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

猜你喜欢

转载自blog.csdn.net/weekdawn/article/details/123993869