Vue中路由(router)的详解与使用细节

概要

本文主要介绍Vue中router的基本使用

路由跳转

1.基本使用

使用vue-router的步骤:

​  第一步:创建路由需要映射的组件(打算显示的页面);

​  第二步:通过createRouter创建路由对象,并且传入routes和 history模式;

​ ✓ 配置路由映射: 组件和路径映射关系的routes数组;

​ ✓ 创建基于hash或者history的模式;

​  第三步:使用app注册路由对象(use方法);

​  第四步:路由使用: 通过和;

  • 在router文件夹下创建index.js
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: HomeView
    },
    {
      path: '/about',
      component: () => import('../views/AboutView.vue')
    }
  ]
})

export default router
  • 在main.js中使用
import { createApp } from 'vue'

import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router)

app.mount('#app')
  • 使用路由
<script setup>
import { RouterLink, RouterView } from 'vue-router'
</script>

<template>
  <!-- 进行路由跳转 -->
  <RouterLink to="/">Home</RouterLink>
  <RouterLink to="/about">About</RouterLink>
  
  <!-- 负责占位,当路由跳转,会把要渲染的组件放到router-view中 -->
  <RouterView />
</template>

<style scoped>
</style>
–router-link属性

to属性:

​  是一个字符串,或者是一个对象

replace属性:

​  设置 replace 属性的话,当点击时,会调用 router.replace(), 而不是 router.push();

active-class属性:

​  设置激活a元素后应用的class,默认是router-link-active

exact-active-class属性:

​  链接精准激活时,应用于渲染的 的 class,默认是router- link-exact-active;

2.路由默认路径 - redirect

  • 可以在路径为 / 时重新定向
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      component: () => import('../views/HomeView.vue')
    }
  ]
})

export default router

3.路由懒加载

{
    path: '/home',
    component: () => import('../views/HomeView.vue')
}

4.路由的其他属性

◼ name属性:路由记录独一无二的名称;

◼ meta属性:自定义的数据

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      // 路由独一无二的属性
      name: 'about',
      // 自定义的属性
      meta: {
        age: 20
      },
      path: '/about',
      component: () => import('../views/AboutView.vue')
    }
  ]
})

export default router

5.动态路由基本匹配

很多时候我们需要将给定匹配模式的路由映射到同一个组件:

​  例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但是用户的ID是不同的;

​  在Vue Router中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数;

{
    // 传入的id是不同的,但是跳转的页面一样
    path: '/user/:id',
    component: () => import('../views/user.vue')
}
– 获取动态参数的值
<template>
    <div class="">
        user{{ $route.params.id }}
    </div>
</template>

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute()
console.log(route.params.id);
</script>

<style scoped></style>

6.NotFound

{
    path: '/:pathMath(.*)',
    component: () => import('../views/notfound.vue')
}

7.路由嵌套

什么是路由的嵌套呢?

​  目前我们匹配的Home、About、User等都属于第一层路由,我们在它们之间可以来回进行切换;

但是呢,我们Home页面本身,也可能会在多个组件之间来回切换:

​  比如Home中包括Product、Message,它们可以在Home内部来回切换;

​  这个时候我们就需要使用嵌套路由,在Home中也使用 router-view 来占位之后需要渲染的组件;

– 路由嵌套配置
{
    path: "/about",
    component: () => import("../views/AboutView.vue"),
    children: [
        {
            path: '',
            redirect: '/about/product'
        },
        {
            path: "product",
            component: () => import("../views/product.vue"),
        }
    ]
},
  • 在About中也要有占位符
<template>
  <div class="about">
    <h1>This is an about page</h1>

    <RouterView></RouterView>
  </div>
</template>

8.代码的页面跳转

◼ 我们可以通过 useRouter 来获取

◼ 我们也可以通过query的方式来传递参数

const router = useRouter()
function jumpTo(){
  router.push({
    path: '/user/123',
    query: {
      age: 20
    }
  })
}

router的go方法:

router.go(1)

router也有back:

 通过调用 history.back() 回溯历史。相当于 router.go(-1);

router也有forward:

 通过调用 history.forward() 在历史中前进。相当于 router.go(1);

9.动态添加路由

某些情况下我们可能需要动态的来添加路由:

​  比如根据用户不同的权限,注册不同的路由;

​  这个时候我们可以使用一个方法 addRoute;

  • 在router文件夹下的index文件进行

const categoryRouter = {
  path: 'moment',
  component: () => import("../views/user.vue")
}

router.addRoute(categoryRouter)

10.路由导航守卫

  • beforeEach,只要是进行路由跳转前都会执行

  • 在进入某个页面前,我们可能需要它已经登录了

  • 路由导航守卫就是在进行路由跳转时进行拦截

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。

全局的前置守卫beforeEach是在导航触发时会被回调的:

它有两个参数:

​  to:即将进入的路由Route对象;

​  from:即将离开的路由Route对象;

它有返回值:

​  false:取消当前导航;

​  不返回或者undefined:进行默认导航;

​  返回一个路由地址:

​ ✓ 可以是一个string类型的路径;

​ ✓ 可以是一个对象,对象中包含path、query、params等信息;

router.beforeEach((to, from) => {
  // 当token不存在返回登录页
    if (!token) {
      return '/login'    
    }

});
– 其他导航守卫(了解)

Vue还提供了很多的其他守卫函数,目的都是在某一个时刻给予我们回调,让我们可以更好的控制程序的流程或者功能:

 https://next.router.vuejs.org/zh/guide/advanced/navigation-guards.html

◼ 我们一起来看一下完整的导航解析流程

 导航被触发。

 在失活的组件里调用 beforeRouteLeave 守卫。

 调用全局的 beforeEach 守卫。

 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。

 在路由配置里调用 beforeEnter。

 解析异步路由组件。

 在被激活的组件里调用 beforeRouteEnter。

 调用全局的 beforeResolve 守卫(2.5+)。

 导航被确认。

 调用全局的 afterEach 钩子。

 触发 DOM 更新。

 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

小结

本文主要提供Vue中router的基本使用
由于作者水平有限
如果对本文有任何疑问可以私信或者评论区发表你的看法
本文如果对你有帮助,麻烦点个赞和收藏方便回看,求关注 谢谢

  • 24
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值