vue3项目路由同时拥有了hash模式与history模式的效果
开发了大半年的功能一直用的是hash模式 今天领导突然说 我们的项目链接为什么会有一个这么丑的#号,既然领导提出不满我们这些打工仔把问题解决了就行
也就一个配置的事情,原先的配置是 history:createWebHashHistory()现在改成了history:createWebHistory()
页面中测试了一下 点了几个按钮正常访问#号被去掉了 但是我在地址栏中访问的时候会在结尾给我加上#/这就很奇怪了
找了配路由的地方 也确认了就是用的history模式 ai提示我项目中使用的还是hash模式,仔细看了router文件以及main.ts文件
export const setRouter = async function () { await loadRoutes(); console.log(routes, "routes"); router = createRouter({ history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY), routes: routes, scrollBehavior(to, from, savedPosition) { return new Promise(resolve => { if (savedPosition) { return savedPosition; } else { if (from.meta.saveSrollTop) { const top: number = document.documentElement.scrollTop || document.body.scrollTop; resolve({ left: 0, top }); } } }); } });
function getHistoryMode(routerHistory): RouterHistory { // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1 const historyMode = routerHistory.split(","); const leftMode = historyMode[0]; const rightMode = historyMode[1]; // no param if (historyMode.length === 1) { if (leftMode === "hash") { return createWebHashHistory(""); } else if (leftMode === "h5") { // return createWebHistory(import.meta.env.VITE_PUBLIC_PATH); return createWebHistory("/"); } } //has param else if (historyMode.length === 2) { if (leftMode === "hash") { return createWebHashHistory(rightMode); } else if (leftMode === "h5") { return createWebHistory(rightMode); } } }
上面代码一直用的是history模式
但是在main.ts中发现多了一行代码
//historyIn = createWebHashHistory(""); routerIn = await setRouter(
//historyIn
);
实际上setRouter并未接受参数 但是直接执行createWebHashHistory()函数就会对整个项目造成影响
将代码注释掉后 问题得以解决
代码搬运工

浙公网安备 33010602011771号