vue-router的history路由模式,跳转路由后出现404页面或者跳转到了网站首页

vue-router的history模式,跳转路由后出现404页面或者跳转到了网站首页。

今天来解决一个大家在做项目时遇到的常见问题。我们的路由一般都是用history路由模式,不仅链接美观,虽然hash路由模式也能实现,但是在公司网站地址携带一个"/#",这样看起来不是很正规。领导要求是能不用hash路由就不用。

Hash模式和History模式的区别
在这里插入图片描述
所以history模式的情况下,如果你不用跳转路由,就一个页面的情况下,可以不用另外配置服务器的路由规则。
那看看我的代码,我是vue3项目,使用vite和vue-router4。

router/index.js

import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/index.vue";
// 定义路由
const routes = [
    {
        path: "/",
        redirect: "/index.html",
    },
    {
        path: "/index.html",
        name: "Home",
        meta: { title: "活动页面" },
        component: Home,
    },
    {
        path: "/clock",
        name: "clock",
        meta: { title: "其他页面" },
        component: () => import("../views/clock.vue"),
    },
    {
        path: "/clock-detail",
        name: "clock-detail",
        meta: { title: "其他详情页面" },
        component: () => import("../views/clock-detail.vue"),
    }
];

// 创建路由实例并配置路由历史模式 
const router = createRouter({
    history: createWebHistory("/2025hd/"),  // 子路径,例如你的项目要部署到 https://www.baidu.com/2025hd/
    routes,
});  

// 全局后置钩子,在路由切换完成后设置页面标题
router.afterEach((to) => {
    if (to.meta.title) {
        document.title = to.meta.title;
    } else {
        document.title = "活动页面";
    }
});

router.beforeEach((to, from, next) => {
    next();
});
export default router;

vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
    base: "./", 
    plugins: [vue()],
    server: {
        port: 3000, //端口
        proxy: {
            "/api": {
                target: "xxxxxxx", 
                changeOrigin: true, //开启跨域
                rewrite: (path) => path.replace(/^\/api/, ""),
            },
        },
    }
});

我的服务器是nginx,在nginx.conf 里面加上一条路由规则

server
{
    ## ...保留原有默认配置
    
    ## 新增这两条配置
    location /2025hd/ { ## /2025hd/跟history路由地址一样,也要和部署路径一样
        try_files $uri $uri/ /2025hd/index.html; 
    }

    location / {
        try_files $uri $uri/ /index.html;   ## 
    }
}

配置好这些后重新打包上线,跳转路由再刷新页面,不会在出现404或者跳转到网站首页的问题啦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿珍敲code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值