在这里插入图片描述

修改文件

修改vue3.0项目下的router/index 文件

history路由

使用 createWebHistory 方法

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

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

export default router

Hash 路由

使用 createWebHashHistory 方法

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

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

history 路由和hash 路由的区别

hash

hash即URL中“#”字符后面的部分。
在这里插入图片描述
实现的原理大致如下
通过 window.location.hash属性获取和设置hash值
通过 window.addEventListener(‘hashchange’,function(e) { console.log(e.oldURL) }); 监听hash值得变化
根据不同的hash值改变页面的渲染

整个过程,通过前端即可实现,无需后端配合,刷新页面并不会报404,但现如今大多数网页采用的还是history模式。

history

实现的原理大致如下
通过pushstate改变当前浏览器路由,并追加浏览器历史记录,但不会更新页面,即浏览器不会向服务器发送请求。
通过popstate来监听浏览器前进后退的变化,当再次进入pushState进入过的路由时,会触发监听事件,改变页面的渲染。
通过前端的配置,不同的路由对应不同的页面,从而渲染出来。

需要注意的是
history模式开发的SPA项目,需要服务器端做额外的配置,否则会出现刷新白屏(链接分享失效)。
原因是页面刷新时,浏览器会向服务器真的发出对这个地址的请求,而这个文件资源又不存在,所以就报404。
处理方式就由后端做一个保底映射:所有的请求全部拦截到index.html上。
history模式的原理采用了H5的新特性pushstate,因此ie >= 10 的浏览器才能够使用,兼容性上有一定要求。
在这里插入图片描述
关于浏览器路由的相关介绍
https://blog.csdn.net/glorydx/article/details/122969486

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐