Vue3中使用Router进行路由配置(图文详情)

Vue3中使用Router进行路由配置

Vue Router 简介

Vue Router 是 Vue.js 官方的路由管理器,它允许您在单页面应用程序(SPA, Single Page Application)中实现导航和页面切换,而无需重新加载整个页面。通过 Vue Router,您可以定义多个路由,每个路由可以映射到不同的组件,并且可以根据 URL 的变化动态地渲染相应的组件。

Vue Router 提供了丰富的功能,包括:

  • 声明式路由配置:通过简单的配置对象来定义路由规则。
  • 嵌套路由:支持父子路由嵌套,方便构建复杂的页面结构。
  • 编程式导航:通过 JavaScript 代码进行页面跳转。
  • 路由参数:支持动态路由参数,用于处理 URL 中的变量部分。
  • 导航守卫:提供全局、路由独享和组件内的导航守卫,用于控制页面访问权限或执行某些逻辑。
  • 路由懒加载:按需加载组件,优化应用性能。
  • 滚动行为:控制页面滚动位置,确保用户在导航时有良好的体验。
  • 命名视图:在一个页面中同时显示多个组件。
  • 重定向和别名:支持路由重定向和别名,方便管理和优化 URL。

本文将不在演示vue3基础工程创建,如果还没有vue3项目工程请参考文章:
Vite创建Vue3工程并引入ElementPlus(图文详细)

安装 Vue Router

官网地址:https://router.vuejs.org/zh/introduction.html

安装依赖

npm install vue-router@4

在src下创建router目录,并创建index.js

import { createRouter, createWebHashHistory } from "vue-router";
const routes = [];
const router = createRouter({
	history: createWebHashHistory(),
	routes
});

export default router;

在main.js下引入router

import router from "./router";
app.use(router);

image-20241222201432242

在src下新建pages文件夹,新建index.vue和about.vue

index.vue

<template>
	<div>index</div>
</template>

<script setup>
	import {} from "vue";
</script>

<style lang="scss" scoped></style>

about.vue

<template>
	<div>about</div>
</template>

<script setup>
	import {} from "vue";
</script>

<style lang="scss" scoped></style>

image-20241222214558468

在router的index.js中加入路由页面

import Index from "@/pages/index.vue";
import About from "@/pages/about.vue";
const routes = [
	{
		path: "/",
		component: Index
	},
	{
		path: "/about",
		component: About
	}
];

image-20241223120555769

在App.vue中加入路由引入

<template>
	<router-view />
</template>

<script setup></script>

<style lang="scss" scoped></style>

npm run dev启动运行项目后,打开浏览器查看路由效果

/根路径下

image-20241222214901249

/about路径下

image-20241222214944118

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值