跳至主要內容

不同的历史模式

刘春龙原创...大约 1 分钟WEB前端Vue3路由教程文档

在创建路由器实例时,history 配置允许我们在不同的历史模式中进行选择

Hash 模式

hash 模式是用 createWebHashHistory() 创建的

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

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home/home.vue')
    },
    {
      path: '/about',
      name: 'about',
    }
  ]
})

export default router



 














HTML5 模式

createWebHistory() 创建 HTML5 模式,推荐使用这个模式

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

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home/home.vue')
    },
    {
      path: '/about',
      name: 'about',
    }
  ]
})

export default router



 














当使用这种历史模式时,URL 会看起来很 "正常",例如 https://example.com/user/id 十分漂亮!

不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/XXX,就会得到一个 404 错误。这就丑了。

你可以自定义一个我错误页面,并进行错误路由的匹配配置

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

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home/home.vue')
    },
    {
      path: '/about',
      name: 'about',
    },
    {
      path: '/:pathMatch(.*)',
      name: 'error',
      component: () => import('@/views/error/error.vue')
    }
  ]
})

export default router














 
 
 
 
 




这样,你再去访问一个路由中不存在的页面地址,就会进入这个漂亮的错误页面了

警告

错误页面的路由配置一定要放在最下面,因为*号代表匹配所有,放在上边的话即使访问存在的页面也会将其匹配上


使用该模式进行开发,项目打包上线后会遇到刷新404的问题,需要在nginx里面进行伪静态的配置

上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7