前端路由

前端路由的整个过程发生在路由器端,其特点是当url地址改变时不需要向后端发送请求

vue router 安装

npm install vue-router

npm

命令 作用 保存到 package.json 的哪个字段
npm install package 安装并保存依赖 dependencies
npm install package --save 同上(显式指定) dependencies
npm install package --save-dev 安装开发依赖 devDependencies
npm install package --save-optional 安装可选依赖 optionalDependencies
npm install package --no-save 安装但不保存 不保存

路由重定向

路由重定向可以使用户在访问一个URL地址时,强制跳转到另一个URL地址,从而展示特定的组件。通过路由匹配规则中的redirect属性可以指定一个新的路由地址,从而实现路由重定向

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/home', component: import ('./components/Home.vue') },
    { path: '/about', component: import('./components/About.vue') }
  ]
})

嵌套路由

routes: [
  {
    path: '父路由路径', 
    component: 父组件,
    children: [
      { path: '子路由路径1', component: 子组件1 },
      { path: '子路由路径2', component: 子组件2 }
    ]
  }
]

注意 子路由不要加/ 不然就是根据根路由

动态路由

{path:'/sub/:id',component:组件}

获取动态路径参数值

  1. 使用$route.params
使用props
  1. 使用props接收路由规则中匹配到的参数。
<template>
  <p>电影{{ id }}页面</p>
</template>
<script setup>
const props = defineProps({
  id: String
})
</script>

  1. 在src\router.js文件中,为“:id”路径的路由开启props传参。
{
  path: ':id', 
  component: () => import ('./components/movieDetails.vue'), 
  props: true 
}

命名路由

在定义路由匹配规则时,使用name属性为路由匹配规则定义路由名称,即可实现命名路由。当路由匹配规则有了路由名称后,在定义路由链接或执行某些跳转操作时,可以直接通过路由名称表示相应的路由,不再需要通过路由路径表示相应的路由。

{ path: '路由路径', name: '路由名称', component: 组件 }
<router-link :to="{ name: 路由名称, params: { 参数名: 参数值 } }"></router-link>

在< router-link>标签中使用命名路由时,需要动态绑定to属性的值为对象。当使用对象作为to属性的值时,to前面要加一个冒号,表示使用v-bind指令进行绑定。在对象中,通过name属性指定要跳转到的路由名称,使用params属性指定跳转时携带的路由参数,语法格式如下。

编程式导航

Vue Router提供了useRouter()函数,使用它可以获取全局路由实例,该全局路由实例中提供了常用的push()方法、replace()方法和go()方法,获取全局路由实例的示例代码如下。

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
</script>

push()

router.push('/about/tab1')			// 字符串路径
router.push({ path: '/about/tab1' })		// 带有路径的对象
router.push({ name: 'user', params: { userId: '123'} })	// 命名路由
router.push({ path: '/user', query: { id: '1' } })		// 带查询参数,如:/user?id=1
router.push({ path: '/user', hash: '#admin' })		// 带有Hash值,如:/user#admin

如果在参数的对象中提供了path,则params会被忽略。为了传递参数,需要提供路由的name或者手动拼接带有参数的path,示例代码如下。

const id = '123'
router.push({ name: '/user', params: { userId } })	// 跳转到/user/123
router.push({ path: `/user/${userId}` })           	// 跳转到/user/123
// 以下是params不生效的情况
router.push({ path: '/user', params: { userId } })	// 跳转到/user

replace()

我的理解不会向router堆中添加url 而是代替最上面的url,而push()会添加url

// 编程式导航
router.replace({ path: '/user' })
<!-- 声明式导航 -->
<router-link :to="{ path: '/user' }" replace></router-link>

go()

go()方法用于实现前进或后退的效果,其参数表示历史记录中前进或后退的步数,类似于window.history.go(),相应的地址栏也会发生改变。

go(1)表示前进一条记录。
go(-1)表示后退一条记录

导航守卫

登陆功能的示例
在这里插入图片描述

全局导航守卫

包括全局前置守卫beforeEach()和全局后置守卫afterEach(),在路由即将改变前和改变后进行触发。

全局导航守卫会拦截每个路由规则,从而对每个路由进行访问权限的控制,定义全局导航守卫的示例代码如下。

const router = createRouter()
router.beforeEach((to, from, next) => {})//路由访问前
router.afterEach((to, from, next) => {})//路由访问和

每个全局导航守卫方法中接收3个形参:to、from和next。
to:表示目标路由对象;
from:表示当前导航正要离开的路由对象;
next:next为函数,如果不接收next()函数,则默认允许用户访问每一个路由;如果接收了next()函数,则必须调用next()函数,否则不允许用户访问任何一个路由。

next()函数具有3种调用方式,分别为next()、next(false)和next(‘/’),其中,next()表示执行下一个钩子函数;next(false)表示强制停留在当前页面;next(‘/’)表示跳转到其他地址。

import { createRouter, createWebHistory } from 'vue-router';
import userfrom from '../components/form/userfrom.vue'
import register from '../components/form/register.vue'
import bookLogin from '../components/booklist/bookLogin.vue'
import headers from '../components/header/headers.vue'
import collect from '../components/collect/collect.vue'
import datail from '../components/collect/datail.vue'
const routes = [{ path: '/user', component: userfrom }, { path: '/register', component: register }, { path: '/', component: headers }, { path: '/list', component: bookLogin }, { path: '/collect', component: collect, meta: { requiresAuth: true } }, {path:'/datail/:id',component:datail}]
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes });
router.beforeEach((to, from, next) => {//前置守卫
  const token = localStorage.getItem("token");
  if (to.meta.requiresAuth && !token) {
    next("/user")
  } else {
    next()
  }
})
export default router;

导航独享守卫

目前只有beforeEnter()守卫,只有在路由导航到一个不同的页面时才会被触发, beforeEnter()守卫只适用于单个路由。

组件导航守卫

包括beforeRouteEnter()、beforeRouteUpdate()、beforeRouteLeave()3个守卫,分别表示在路由进入之前被触发、在路由更新之前被触发、在路由离开之前被触发。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐