vue3.0路由的两种方式

发布时间 2023-05-30 11:20:16作者: ╰透在骨子里的小傲娇
import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('./pages/index.vue') // 异步加载
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

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

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('./pages/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

createWebHashHistory

  • 形式:http://localhost:8080/#/
  • 原理:a标签锚点链接
  • hash 模式下,仅hash符号之前的内容会被包含在请求中,如http://www.abc.com,因此对于后端来说,即使没有做到对路由的全覆盖,也不会返回404错误。

createWebHistory

  • 形式:http://localhost:8080/
  • 原理:H5 pushState()
  • 此种方式,需要后台配合做重定向,否则会出现404问题。
  • 当我们进行项目的主页的时候,一切正常,可以访问,但是当我们刷新页面或者直接访问路径的时候就会返回404,那是因为在history模式下,只是动态的通过js操作window.history来改变浏览器地址栏里的路径,并没有发起http请求,但是当我直接在浏览器里输入这个地址的时候,就一定要对服务器发起http请求,但是这个目标在服务器上又不存在,所以会返回404。