vuejs3.0 从入门到精通——初始化项目——路由

路由

  Vue Router 是 Vue.js 官方的路由管理器,它和 Vue.js 深度集成,用于构建单页面应用。Vue.js 单页面应用是基于路由和组件映射的,路由用于配置访问路径,将组件(components)映射到路由路径(routes)。

一、路由模式

  Vue Router 常用的两种模式是 hash 模式和 HTML5 模式,对应的创建模式分别是 create WebHashHistory 和 createWebHistory。

    • createWebHashHistory 模式:
    • createWebHistory 模式:

1.1、createWebHashHistory模式

  创建 hash 历史记录。指浏览器地址栏 URL 的#(此 hash 不是密码学中的散列运算),如 http://www.abc.com/#/hello,其中的#/hello 为 hash 值。它的特点在于 hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面。

1.2、createWebHistory模式

  创建 HTML5 历史记录。在浏览器的历史记录栈中利用 HTML5 的 History Interface 新增的 pushState 和 replaceState 方法,在当前已有的 back、forward、go 基础上,它们提供了修改历史记录的功能。当它们执行修改时,虽然改变了目前的 URL,但浏览器不会立即向后端发送请求。

  在Vue 3中,createWebHashHistorycreateWebHistory的区别确实在于URL中是否带有哈希符号“#”。

  • createWebHashHistory:

当使用createWebHashHistory创建Vue Router实例时,URL中的路径将以哈希形式呈现,即带有“#”符号。例如,如果当前路由是“/user/profile”,则URL将显示为“http://example.com/#/user/profile”。

这种模式在老版本的浏览器中通常被使用,因为它允许通过URL的哈希部分来标识每个路由,而不需要使用HTML5 History API。然而,现代浏览器大多都支持HTML5 History API,因此使用createWebHistory可能更加适合。

  • createWebHistory:

当使用createWebHistory创建Vue Router实例时,URL中的路径将以常规形式呈现,即不带有“#”符号。例如,如果当前路由是“/user/profile”,则URL将显示为“http://example.com/user/profile”。

这种模式在现代浏览器中更为常见,因为它利用了HTML5 History API来管理路由历史记录。它还允许使用浏览器的标准前进和后退按钮进行导航,而不需要依赖URL的哈希部分。

  选择使用createWebHashHistory还是createWebHistory取决于你的应用需求和目标浏览器的支持情况。

  如果你需要兼容老版本的浏览器或特定的环境,并且不需要使用HTML5 History API,那么使用createWebHashHistory可能更合适。否则,现代浏览器大多都支持HTML5 History API,因此使用createWebHistory可能更加适合。

二、路由定义

  对路由的定义可通过路由名称进行标识,特别是在链接一个路由或执行路由跳转时,可以在创建 Router 实例时在 routes 配置中给路由设置名称。

  在 Vue 3 中,路由的定义通常在router.js文件或router/index.js中进行。以下是一个示例代码,展示了如何在 Vue 3 中使用createWebHistorycreateWebHashHistory,并使用路由名称在链接或执行路由跳转时进行标识:

// router/index.js
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import UserComponent from './components/UserComponent.vue';
import ProfileComponent from './components/ProfileComponent.vue';

// 定义路由映射组件
const routes = [
    {
        path: '/user/:id',
        name: 'User',
        component: UserComponent
    },
    {
        path: '/user/:id/profile',
        name: 'Profile',
        component: ProfileComponent
    }
];

// 创建 Router 实例(使用 createWebHistory 或 createWebHashHistory)
const router = createRouter({
    history: createWebHistory(), // 或 createWebHashHistory()
    routes
});

export default router;

  在上面的示例中,我们定义了两个路由:UserProfile,它们分别映射到UserComponentProfileComponent组件。我们使用name属性为每个路由设置了一个名称,以便在链接或执行路由跳转时使用。

  接下来,你可以在其他 Vue 组件中使用<router-link><router-view>来链接和渲染路由:

<!-- SomeComponent.vue -->
<template>
  <div>
    <h1>导航</h1>
    <router-link to="/user/1">User</router-link>
    <router-link to="/user/1/profile">Profile</router-link>

    <h2>内容</h2>
    <router-view></router-view>
  </div>
</template>

  在上面的示例中,我们使用<router-link>创建了两个导航链接,分别链接到UserProfile路由。我们还使用<router-view>来渲染当前路由所对应的组件。

posted @ 2023-11-01 10:42  左扬  阅读(171)  评论(0编辑  收藏  举报
levels of contents