vue-router之路由模式

vue-router中默认使用的是hash模式。,在URL中带有#号。

vue-router中存在的路由模式大致分为2种:

Hash: 使用URL的hash值来作为路由。支持所有浏览器。hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面。

History: 以来HTML5 History API 和服务器配置。利用了 HTML5 History Interface 中新增的 pushState() 和 replaceState() 方法。

原理

hash模式灵活运 用了html的瞄点功能、改变#后的路径本质上是更换了当前页面的瞄点,所以不会刷新页面。

history是使用了 H5 提供的pushState() 和 replaceState(),允许开发者直接更改前端路由,即更新浏览器 URL 地址而不重新发起请求(将url替换并且不刷新页面)。

如何使用hash模式?

  1. hash模式:在路由index.js文件中导入 createWebHashHistory
    import { createRouter, createWebHashHistory } from "vue-router";
  2. 在路由index.js文件中导入注册使用 createWebHashHistory
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

如何使用history模式?

  1. hash模式:在路由index.js文件中导入 createWebHashHistory
    import {createRouter,createWebHistory} from 'vue-router'
  2. 在路由index.js文件中导入注册使用 createWebHashHistory
const router = createRouter({
  history: createWebHistory(),
  routes
})
posted @ 2022-03-23 00:46  小阿紫  阅读(585)  评论(0)    收藏  举报