Vue3刷新页面报错404

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue3刷新页面报错404

SpongeBob   2022-06-03 我要评论

vue-router历史模式

最近在学习Vue3的过程中遇到了一个问题,那就是在写代码的过程中,每当代码发生了变动,页面一刷新,原先的页面就会变成这个样子:

打开控制台一看:

这时候刷新、在浏览器地址栏直接输入地址也不管用。 每次写一点代码,都不能及时看到结果,需要从8080重新进入才可以,其中的崩溃可想而知。 此时判断应该是路由跳转的问题,于是来到router.js文件看一看:

import {
  createRouter,
  createWebHistory
} from 'vue-router'
// import Home from '../views/Home.vue'

const Home = () => import('../views/home/Home');
const Category = () => import('../views/category/Category');
const Detail = () => import('../views/detail/Detail');
const Profile = () => import('../views/profile/Profile');
const Shopcart = () => import('../views/shopcart/Shopcart');


const routes = [{
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '图书兄弟'
    }
  },
  {
    path: '/',
    name: 'Default',
    component: Home,
    meta: {
      title: '图书兄弟'
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: Category,
    meta: {
      title: '商品分类'
    }
  },
  {
    path: '/detail',
    name: 'Detail',
    component: Detail,
    meta: {
      title: '商品详情'
    }
  },

  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: {
      title: '个人中心'
    }
  },
  {
    path: '/shopcart',
    name: 'Shopcart',
    component: Shopcart,
    meta: {
      title: '购物车'
    }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


router.beforeEach((to, from, next) => {

  // 如果没有登录,到login
  next();
  document.title = to.meta.title;
})

export default router

感觉没啥问题,仔细检查了自己写的代码部分,没有发现问题,于是更纳闷了,难道是自动生成的代码出现了问题? 经过一翻排查,发现原来是vue-router历史模式的问题: vue3中历史模式默认改为了HTML5模式:createWebHistory()

当使用这种历史模式时,URL 会看起来很 "正常",例如 https://example.com/user/id。 不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/id,就会得到一个 404 错误。 这就是一直折磨我的罪魁祸首!

Vue-router官方给出的解决方案是:

要解决这个问题,你需要做的就是在你的服务器上添加一个简单的回退路由。如果 URL 不匹配任何静态资源,它应提供与你的应用程序中的 index.html 相同的页面。

这涉及到服务器的配置,由于我的项目还在开发阶段,所以这种解决方式暂时不能用。所幸还有其他的解决方案,那就是将历史模式由当前的HTML5模式改为Hash模式:

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    //...
  ],
})

表现在代码上就是两个createWebHistory换成了createWebHashHistory,这样就完成了修改。

修改完成后重新启动项目:

npm run serve

此时刷新页面也不会报404了,大功告成!

详细解决方法请移步vue-router官网“不同的历史记录模式”部分: router.vuejs.org/zh/guide/essentials/history-mode.html

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们