共计 1638 个字符,预计需要花费 5 分钟才能阅读完成。
一、Vue Router 的两种路由模式
哈希模式(Hash Mode)
默认模式,URL 结构包含哈希符号 #,例如:http://example.com/#/home。利用 window.location.hash 来跟踪路由变化,浏览器会自动处理哈希的变化而不触发页面重载。
因为哈希值只影响浏览器的历史记录而不发送到服务器,所以无需后端配合即可实现前端路由。
SEO 性能较差,因为搜索引擎通常不会抓取哈希值后面的路径内容。
历史模式(History Mode)
利用了 HTML5 的 History API,如 window.history.pushState() 和 window.onpopstate 事件。
在此模式下,URL 不包含哈希,呈现常规的路径结构,例如:http://example.com/home。
为了实现前进、后退按钮的正常工作以及防止直接访问某个路由导致 404 错误,需要在服务器端进行适当的配置,将所有的请求都指向应用程序的入口文件,以便 Vue Router 能够接管并解析正确的路由。
历史模式提高了用户体验,URL 易于阅读,也更利于 SEO。
二、History 路由 模式打包部署项目
在 Vue 3. 中使用 Vue Router 的 history 模式进行项目打包部署时,需要确保打包配置和服务器正确配置来处理路由。否则部署到 Nginx 会出现访问 404、空白等。在项目打包配置及 Nginx 配置有些要注意的地方。以项目名 demo 为例。
1、配置 Vue Router 为 history 模式,在 src/router/index.js
中配置
import {createRouter, createWebHistory} from 'vue-router'
const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),
routes:[// 定义路由]
})
export default router
备注:createWebHistory:history 模式,createWebHashHistory:hash 模式
2、配置 vite.config.js
import {
fileURLToPath,
URL
} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig(() => {
return {
plugins: [vue()
],
// 静态站点根路径配置;base:'/demo/';demo 是项目名,解决 Nginx 部署时,访问缺少项目前缀的问题
base: process.env.NODE_ENV === 'production' ? '/demo/' : '/',// vue-router 中配置,组件匹配
// publicPath: process.env.NODE_ENV === 'production' ? '/demo/' : '/',// vue.config.js 文件中配置,打包后外部资源的获取
build: {
// 设置打包文件夹的名称
outDir: 'demo'
},
resolve: {
alias: {'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
};
});
3、配置 Nginx,在 conf/nginx.conf 中配置
location /demo/ {
alias /path/html/demo/;
index index.html index.htm;
try_files $uri $uri/ /demo/index.html;
}
备注:alias /path/html/demo/; 中的 path 换成 Nginx 对应的部署路径
原文地址: vue3 vite 使用 History 路由模式打包部署项目注意事项